PageRenderTime 65ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/ext/scintilla/src/Document.cxx

https://gitlab.com/JeevRobinson/tortoisegit
C++ | 2820 lines | 2408 code | 224 blank | 188 comment | 881 complexity | abc9d1f76baa83fbdd1917e385cb431d MD5 | raw file
Possible License(s): GPL-3.0, LGPL-3.0, MPL-2.0-no-copyleft-exception, GPL-2.0, LGPL-2.0
  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-2011 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 <assert.h>
  11. #include <ctype.h>
  12. #include <stdexcept>
  13. #include <string>
  14. #include <vector>
  15. #include <algorithm>
  16. #ifdef CXX11_REGEX
  17. #include <regex>
  18. #endif
  19. #include "Platform.h"
  20. #include "ILexer.h"
  21. #include "Scintilla.h"
  22. #include "CharacterSet.h"
  23. #include "SplitVector.h"
  24. #include "Partitioning.h"
  25. #include "RunStyles.h"
  26. #include "CellBuffer.h"
  27. #include "PerLine.h"
  28. #include "CharClassify.h"
  29. #include "Decoration.h"
  30. #include "CaseFolder.h"
  31. #include "Document.h"
  32. #include "RESearch.h"
  33. #include "UniConversion.h"
  34. #include "UnicodeFromUTF8.h"
  35. #ifdef SCI_NAMESPACE
  36. using namespace Scintilla;
  37. #endif
  38. static inline bool IsPunctuation(char ch) {
  39. return IsASCII(ch) && ispunct(ch);
  40. }
  41. void LexInterface::Colourise(int start, int end) {
  42. if (pdoc && instance && !performingStyle) {
  43. // Protect against reentrance, which may occur, for example, when
  44. // fold points are discovered while performing styling and the folding
  45. // code looks for child lines which may trigger styling.
  46. performingStyle = true;
  47. int lengthDoc = pdoc->Length();
  48. if (end == -1)
  49. end = lengthDoc;
  50. int len = end - start;
  51. PLATFORM_ASSERT(len >= 0);
  52. PLATFORM_ASSERT(start + len <= lengthDoc);
  53. int styleStart = 0;
  54. if (start > 0)
  55. styleStart = pdoc->StyleAt(start - 1);
  56. if (len > 0) {
  57. instance->Lex(start, len, styleStart, pdoc);
  58. instance->Fold(start, len, styleStart, pdoc);
  59. }
  60. performingStyle = false;
  61. }
  62. }
  63. int LexInterface::LineEndTypesSupported() {
  64. if (instance) {
  65. int interfaceVersion = instance->Version();
  66. if (interfaceVersion >= lvSubStyles) {
  67. ILexerWithSubStyles *ssinstance = static_cast<ILexerWithSubStyles *>(instance);
  68. return ssinstance->LineEndTypesSupported();
  69. }
  70. }
  71. return 0;
  72. }
  73. Document::Document() {
  74. refCount = 0;
  75. pcf = NULL;
  76. #ifdef _WIN32
  77. eolMode = SC_EOL_CRLF;
  78. #else
  79. eolMode = SC_EOL_LF;
  80. #endif
  81. dbcsCodePage = 0;
  82. lineEndBitSet = SC_LINE_END_TYPE_DEFAULT;
  83. endStyled = 0;
  84. styleClock = 0;
  85. enteredModification = 0;
  86. enteredStyling = 0;
  87. enteredReadOnlyCount = 0;
  88. insertionSet = false;
  89. tabInChars = 8;
  90. indentInChars = 0;
  91. actualIndentInChars = 8;
  92. useTabs = true;
  93. tabIndents = true;
  94. backspaceUnindents = false;
  95. matchesValid = false;
  96. regex = 0;
  97. UTF8BytesOfLeadInitialise();
  98. perLineData[ldMarkers] = new LineMarkers();
  99. perLineData[ldLevels] = new LineLevels();
  100. perLineData[ldState] = new LineState();
  101. perLineData[ldMargin] = new LineAnnotation();
  102. perLineData[ldAnnotation] = new LineAnnotation();
  103. cb.SetPerLine(this);
  104. pli = 0;
  105. }
  106. Document::~Document() {
  107. for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
  108. it->watcher->NotifyDeleted(this, it->userData);
  109. }
  110. for (int j=0; j<ldSize; j++) {
  111. delete perLineData[j];
  112. perLineData[j] = 0;
  113. }
  114. delete regex;
  115. regex = 0;
  116. delete pli;
  117. pli = 0;
  118. delete pcf;
  119. pcf = 0;
  120. }
  121. void Document::Init() {
  122. for (int j=0; j<ldSize; j++) {
  123. if (perLineData[j])
  124. perLineData[j]->Init();
  125. }
  126. }
  127. int Document::LineEndTypesSupported() const {
  128. if ((SC_CP_UTF8 == dbcsCodePage) && pli)
  129. return pli->LineEndTypesSupported();
  130. else
  131. return 0;
  132. }
  133. bool Document::SetDBCSCodePage(int dbcsCodePage_) {
  134. if (dbcsCodePage != dbcsCodePage_) {
  135. dbcsCodePage = dbcsCodePage_;
  136. SetCaseFolder(NULL);
  137. cb.SetLineEndTypes(lineEndBitSet & LineEndTypesSupported());
  138. return true;
  139. } else {
  140. return false;
  141. }
  142. }
  143. bool Document::SetLineEndTypesAllowed(int lineEndBitSet_) {
  144. if (lineEndBitSet != lineEndBitSet_) {
  145. lineEndBitSet = lineEndBitSet_;
  146. int lineEndBitSetActive = lineEndBitSet & LineEndTypesSupported();
  147. if (lineEndBitSetActive != cb.GetLineEndTypes()) {
  148. ModifiedAt(0);
  149. cb.SetLineEndTypes(lineEndBitSetActive);
  150. return true;
  151. } else {
  152. return false;
  153. }
  154. } else {
  155. return false;
  156. }
  157. }
  158. void Document::InsertLine(int line) {
  159. for (int j=0; j<ldSize; j++) {
  160. if (perLineData[j])
  161. perLineData[j]->InsertLine(line);
  162. }
  163. }
  164. void Document::RemoveLine(int line) {
  165. for (int j=0; j<ldSize; j++) {
  166. if (perLineData[j])
  167. perLineData[j]->RemoveLine(line);
  168. }
  169. }
  170. // Increase reference count and return its previous value.
  171. int Document::AddRef() {
  172. return refCount++;
  173. }
  174. // Decrease reference count and return its previous value.
  175. // Delete the document if reference count reaches zero.
  176. int SCI_METHOD Document::Release() {
  177. int curRefCount = --refCount;
  178. if (curRefCount == 0)
  179. delete this;
  180. return curRefCount;
  181. }
  182. void Document::SetSavePoint() {
  183. cb.SetSavePoint();
  184. NotifySavePoint(true);
  185. }
  186. void Document::TentativeUndo() {
  187. if (!TentativeActive())
  188. return;
  189. CheckReadOnly();
  190. if (enteredModification == 0) {
  191. enteredModification++;
  192. if (!cb.IsReadOnly()) {
  193. bool startSavePoint = cb.IsSavePoint();
  194. bool multiLine = false;
  195. int steps = cb.TentativeSteps();
  196. //Platform::DebugPrintf("Steps=%d\n", steps);
  197. for (int step = 0; step < steps; step++) {
  198. const int prevLinesTotal = LinesTotal();
  199. const Action &action = cb.GetUndoStep();
  200. if (action.at == removeAction) {
  201. NotifyModified(DocModification(
  202. SC_MOD_BEFOREINSERT | SC_PERFORMED_UNDO, action));
  203. } else if (action.at == containerAction) {
  204. DocModification dm(SC_MOD_CONTAINER | SC_PERFORMED_UNDO);
  205. dm.token = action.position;
  206. NotifyModified(dm);
  207. } else {
  208. NotifyModified(DocModification(
  209. SC_MOD_BEFOREDELETE | SC_PERFORMED_UNDO, action));
  210. }
  211. cb.PerformUndoStep();
  212. if (action.at != containerAction) {
  213. ModifiedAt(action.position);
  214. }
  215. int modFlags = SC_PERFORMED_UNDO;
  216. // With undo, an insertion action becomes a deletion notification
  217. if (action.at == removeAction) {
  218. modFlags |= SC_MOD_INSERTTEXT;
  219. } else if (action.at == insertAction) {
  220. modFlags |= SC_MOD_DELETETEXT;
  221. }
  222. if (steps > 1)
  223. modFlags |= SC_MULTISTEPUNDOREDO;
  224. const int linesAdded = LinesTotal() - prevLinesTotal;
  225. if (linesAdded != 0)
  226. multiLine = true;
  227. if (step == steps - 1) {
  228. modFlags |= SC_LASTSTEPINUNDOREDO;
  229. if (multiLine)
  230. modFlags |= SC_MULTILINEUNDOREDO;
  231. }
  232. NotifyModified(DocModification(modFlags, action.position, action.lenData,
  233. linesAdded, action.data));
  234. }
  235. bool endSavePoint = cb.IsSavePoint();
  236. if (startSavePoint != endSavePoint)
  237. NotifySavePoint(endSavePoint);
  238. cb.TentativeCommit();
  239. }
  240. enteredModification--;
  241. }
  242. }
  243. int Document::GetMark(int line) {
  244. return static_cast<LineMarkers *>(perLineData[ldMarkers])->MarkValue(line);
  245. }
  246. int Document::MarkerNext(int lineStart, int mask) const {
  247. return static_cast<LineMarkers *>(perLineData[ldMarkers])->MarkerNext(lineStart, mask);
  248. }
  249. int Document::AddMark(int line, int markerNum) {
  250. if (line >= 0 && line <= LinesTotal()) {
  251. int prev = static_cast<LineMarkers *>(perLineData[ldMarkers])->
  252. AddMark(line, markerNum, LinesTotal());
  253. DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
  254. NotifyModified(mh);
  255. return prev;
  256. } else {
  257. return 0;
  258. }
  259. }
  260. void Document::AddMarkSet(int line, int valueSet) {
  261. if (line < 0 || line > LinesTotal()) {
  262. return;
  263. }
  264. unsigned int m = valueSet;
  265. for (int i = 0; m; i++, m >>= 1)
  266. if (m & 1)
  267. static_cast<LineMarkers *>(perLineData[ldMarkers])->
  268. AddMark(line, i, LinesTotal());
  269. DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
  270. NotifyModified(mh);
  271. }
  272. void Document::DeleteMark(int line, int markerNum) {
  273. static_cast<LineMarkers *>(perLineData[ldMarkers])->DeleteMark(line, markerNum, false);
  274. DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line);
  275. NotifyModified(mh);
  276. }
  277. void Document::DeleteMarkFromHandle(int markerHandle) {
  278. static_cast<LineMarkers *>(perLineData[ldMarkers])->DeleteMarkFromHandle(markerHandle);
  279. DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0);
  280. mh.line = -1;
  281. NotifyModified(mh);
  282. }
  283. void Document::DeleteAllMarks(int markerNum) {
  284. bool someChanges = false;
  285. for (int line = 0; line < LinesTotal(); line++) {
  286. if (static_cast<LineMarkers *>(perLineData[ldMarkers])->DeleteMark(line, markerNum, true))
  287. someChanges = true;
  288. }
  289. if (someChanges) {
  290. DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0);
  291. mh.line = -1;
  292. NotifyModified(mh);
  293. }
  294. }
  295. int Document::LineFromHandle(int markerHandle) {
  296. return static_cast<LineMarkers *>(perLineData[ldMarkers])->LineFromHandle(markerHandle);
  297. }
  298. int SCI_METHOD Document::LineStart(int line) const {
  299. return cb.LineStart(line);
  300. }
  301. bool Document::IsLineStartPosition(int position) const {
  302. return LineStart(LineFromPosition(position)) == position;
  303. }
  304. int SCI_METHOD Document::LineEnd(int line) const {
  305. if (line >= LinesTotal() - 1) {
  306. return LineStart(line + 1);
  307. } else {
  308. int position = LineStart(line + 1);
  309. if (SC_CP_UTF8 == dbcsCodePage) {
  310. unsigned char bytes[] = {
  311. static_cast<unsigned char>(cb.CharAt(position-3)),
  312. static_cast<unsigned char>(cb.CharAt(position-2)),
  313. static_cast<unsigned char>(cb.CharAt(position-1)),
  314. };
  315. if (UTF8IsSeparator(bytes)) {
  316. return position - UTF8SeparatorLength;
  317. }
  318. if (UTF8IsNEL(bytes+1)) {
  319. return position - UTF8NELLength;
  320. }
  321. }
  322. position--; // Back over CR or LF
  323. // When line terminator is CR+LF, may need to go back one more
  324. if ((position > LineStart(line)) && (cb.CharAt(position - 1) == '\r')) {
  325. position--;
  326. }
  327. return position;
  328. }
  329. }
  330. void SCI_METHOD Document::SetErrorStatus(int status) {
  331. // Tell the watchers an error has occurred.
  332. for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
  333. it->watcher->NotifyErrorOccurred(this, it->userData, status);
  334. }
  335. }
  336. int SCI_METHOD Document::LineFromPosition(int pos) const {
  337. return cb.LineFromPosition(pos);
  338. }
  339. int Document::LineEndPosition(int position) const {
  340. return LineEnd(LineFromPosition(position));
  341. }
  342. bool Document::IsLineEndPosition(int position) const {
  343. return LineEnd(LineFromPosition(position)) == position;
  344. }
  345. bool Document::IsPositionInLineEnd(int position) const {
  346. return position >= LineEnd(LineFromPosition(position));
  347. }
  348. int Document::VCHomePosition(int position) const {
  349. int line = LineFromPosition(position);
  350. int startPosition = LineStart(line);
  351. int endLine = LineEnd(line);
  352. int startText = startPosition;
  353. while (startText < endLine && (cb.CharAt(startText) == ' ' || cb.CharAt(startText) == '\t'))
  354. startText++;
  355. if (position == startText)
  356. return startPosition;
  357. else
  358. return startText;
  359. }
  360. int SCI_METHOD Document::SetLevel(int line, int level) {
  361. int prev = static_cast<LineLevels *>(perLineData[ldLevels])->SetLevel(line, level, LinesTotal());
  362. if (prev != level) {
  363. DocModification mh(SC_MOD_CHANGEFOLD | SC_MOD_CHANGEMARKER,
  364. LineStart(line), 0, 0, 0, line);
  365. mh.foldLevelNow = level;
  366. mh.foldLevelPrev = prev;
  367. NotifyModified(mh);
  368. }
  369. return prev;
  370. }
  371. int SCI_METHOD Document::GetLevel(int line) const {
  372. return static_cast<LineLevels *>(perLineData[ldLevels])->GetLevel(line);
  373. }
  374. void Document::ClearLevels() {
  375. static_cast<LineLevels *>(perLineData[ldLevels])->ClearLevels();
  376. }
  377. static bool IsSubordinate(int levelStart, int levelTry) {
  378. if (levelTry & SC_FOLDLEVELWHITEFLAG)
  379. return true;
  380. else
  381. return (levelStart & SC_FOLDLEVELNUMBERMASK) < (levelTry & SC_FOLDLEVELNUMBERMASK);
  382. }
  383. int Document::GetLastChild(int lineParent, int level, int lastLine) {
  384. if (level == -1)
  385. level = GetLevel(lineParent) & SC_FOLDLEVELNUMBERMASK;
  386. int maxLine = LinesTotal();
  387. int lookLastLine = (lastLine != -1) ? Platform::Minimum(LinesTotal() - 1, lastLine) : -1;
  388. int lineMaxSubord = lineParent;
  389. while (lineMaxSubord < maxLine - 1) {
  390. EnsureStyledTo(LineStart(lineMaxSubord + 2));
  391. if (!IsSubordinate(level, GetLevel(lineMaxSubord + 1)))
  392. break;
  393. if ((lookLastLine != -1) && (lineMaxSubord >= lookLastLine) && !(GetLevel(lineMaxSubord) & SC_FOLDLEVELWHITEFLAG))
  394. break;
  395. lineMaxSubord++;
  396. }
  397. if (lineMaxSubord > lineParent) {
  398. if (level > (GetLevel(lineMaxSubord + 1) & SC_FOLDLEVELNUMBERMASK)) {
  399. // Have chewed up some whitespace that belongs to a parent so seek back
  400. if (GetLevel(lineMaxSubord) & SC_FOLDLEVELWHITEFLAG) {
  401. lineMaxSubord--;
  402. }
  403. }
  404. }
  405. return lineMaxSubord;
  406. }
  407. int Document::GetFoldParent(int line) const {
  408. int level = GetLevel(line) & SC_FOLDLEVELNUMBERMASK;
  409. int lineLook = line - 1;
  410. while ((lineLook > 0) && (
  411. (!(GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG)) ||
  412. ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) >= level))
  413. ) {
  414. lineLook--;
  415. }
  416. if ((GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG) &&
  417. ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) < level)) {
  418. return lineLook;
  419. } else {
  420. return -1;
  421. }
  422. }
  423. void Document::GetHighlightDelimiters(HighlightDelimiter &highlightDelimiter, int line, int lastLine) {
  424. int level = GetLevel(line);
  425. int lookLastLine = Platform::Maximum(line, lastLine) + 1;
  426. int lookLine = line;
  427. int lookLineLevel = level;
  428. int lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
  429. while ((lookLine > 0) && ((lookLineLevel & SC_FOLDLEVELWHITEFLAG) ||
  430. ((lookLineLevel & SC_FOLDLEVELHEADERFLAG) && (lookLineLevelNum >= (GetLevel(lookLine + 1) & SC_FOLDLEVELNUMBERMASK))))) {
  431. lookLineLevel = GetLevel(--lookLine);
  432. lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
  433. }
  434. int beginFoldBlock = (lookLineLevel & SC_FOLDLEVELHEADERFLAG) ? lookLine : GetFoldParent(lookLine);
  435. if (beginFoldBlock == -1) {
  436. highlightDelimiter.Clear();
  437. return;
  438. }
  439. int endFoldBlock = GetLastChild(beginFoldBlock, -1, lookLastLine);
  440. int firstChangeableLineBefore = -1;
  441. if (endFoldBlock < line) {
  442. lookLine = beginFoldBlock - 1;
  443. lookLineLevel = GetLevel(lookLine);
  444. lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
  445. while ((lookLine >= 0) && (lookLineLevelNum >= SC_FOLDLEVELBASE)) {
  446. if (lookLineLevel & SC_FOLDLEVELHEADERFLAG) {
  447. if (GetLastChild(lookLine, -1, lookLastLine) == line) {
  448. beginFoldBlock = lookLine;
  449. endFoldBlock = line;
  450. firstChangeableLineBefore = line - 1;
  451. }
  452. }
  453. if ((lookLine > 0) && (lookLineLevelNum == SC_FOLDLEVELBASE) && ((GetLevel(lookLine - 1) & SC_FOLDLEVELNUMBERMASK) > lookLineLevelNum))
  454. break;
  455. lookLineLevel = GetLevel(--lookLine);
  456. lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
  457. }
  458. }
  459. if (firstChangeableLineBefore == -1) {
  460. for (lookLine = line - 1, lookLineLevel = GetLevel(lookLine), lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
  461. lookLine >= beginFoldBlock;
  462. lookLineLevel = GetLevel(--lookLine), lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK) {
  463. if ((lookLineLevel & SC_FOLDLEVELWHITEFLAG) || (lookLineLevelNum > (level & SC_FOLDLEVELNUMBERMASK))) {
  464. firstChangeableLineBefore = lookLine;
  465. break;
  466. }
  467. }
  468. }
  469. if (firstChangeableLineBefore == -1)
  470. firstChangeableLineBefore = beginFoldBlock - 1;
  471. int firstChangeableLineAfter = -1;
  472. for (lookLine = line + 1, lookLineLevel = GetLevel(lookLine), lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK;
  473. lookLine <= endFoldBlock;
  474. lookLineLevel = GetLevel(++lookLine), lookLineLevelNum = lookLineLevel & SC_FOLDLEVELNUMBERMASK) {
  475. if ((lookLineLevel & SC_FOLDLEVELHEADERFLAG) && (lookLineLevelNum < (GetLevel(lookLine + 1) & SC_FOLDLEVELNUMBERMASK))) {
  476. firstChangeableLineAfter = lookLine;
  477. break;
  478. }
  479. }
  480. if (firstChangeableLineAfter == -1)
  481. firstChangeableLineAfter = endFoldBlock + 1;
  482. highlightDelimiter.beginFoldBlock = beginFoldBlock;
  483. highlightDelimiter.endFoldBlock = endFoldBlock;
  484. highlightDelimiter.firstChangeableLineBefore = firstChangeableLineBefore;
  485. highlightDelimiter.firstChangeableLineAfter = firstChangeableLineAfter;
  486. }
  487. int Document::ClampPositionIntoDocument(int pos) const {
  488. return Platform::Clamp(pos, 0, Length());
  489. }
  490. bool Document::IsCrLf(int pos) const {
  491. if (pos < 0)
  492. return false;
  493. if (pos >= (Length() - 1))
  494. return false;
  495. return (cb.CharAt(pos) == '\r') && (cb.CharAt(pos + 1) == '\n');
  496. }
  497. int Document::LenChar(int pos) {
  498. if (pos < 0) {
  499. return 1;
  500. } else if (IsCrLf(pos)) {
  501. return 2;
  502. } else if (SC_CP_UTF8 == dbcsCodePage) {
  503. const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(pos));
  504. const int widthCharBytes = UTF8BytesOfLead[leadByte];
  505. int lengthDoc = Length();
  506. if ((pos + widthCharBytes) > lengthDoc)
  507. return lengthDoc - pos;
  508. else
  509. return widthCharBytes;
  510. } else if (dbcsCodePage) {
  511. return IsDBCSLeadByte(cb.CharAt(pos)) ? 2 : 1;
  512. } else {
  513. return 1;
  514. }
  515. }
  516. bool Document::InGoodUTF8(int pos, int &start, int &end) const {
  517. int trail = pos;
  518. while ((trail>0) && (pos-trail < UTF8MaxBytes) && UTF8IsTrailByte(static_cast<unsigned char>(cb.CharAt(trail-1))))
  519. trail--;
  520. start = (trail > 0) ? trail-1 : trail;
  521. const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(start));
  522. const int widthCharBytes = UTF8BytesOfLead[leadByte];
  523. if (widthCharBytes == 1) {
  524. return false;
  525. } else {
  526. int trailBytes = widthCharBytes - 1;
  527. int len = pos - start;
  528. if (len > trailBytes)
  529. // pos too far from lead
  530. return false;
  531. char charBytes[UTF8MaxBytes] = {static_cast<char>(leadByte),0,0,0};
  532. for (int b=1; b<widthCharBytes && ((start+b) < Length()); b++)
  533. charBytes[b] = cb.CharAt(static_cast<int>(start+b));
  534. int utf8status = UTF8Classify(reinterpret_cast<const unsigned char *>(charBytes), widthCharBytes);
  535. if (utf8status & UTF8MaskInvalid)
  536. return false;
  537. end = start + widthCharBytes;
  538. return true;
  539. }
  540. }
  541. // Normalise a position so that it is not halfway through a two byte character.
  542. // This can occur in two situations -
  543. // When lines are terminated with \r\n pairs which should be treated as one character.
  544. // When displaying DBCS text such as Japanese.
  545. // If moving, move the position in the indicated direction.
  546. int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) const {
  547. //Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir);
  548. // If out of range, just return minimum/maximum value.
  549. if (pos <= 0)
  550. return 0;
  551. if (pos >= Length())
  552. return Length();
  553. // PLATFORM_ASSERT(pos > 0 && pos < Length());
  554. if (checkLineEnd && IsCrLf(pos - 1)) {
  555. if (moveDir > 0)
  556. return pos + 1;
  557. else
  558. return pos - 1;
  559. }
  560. if (dbcsCodePage) {
  561. if (SC_CP_UTF8 == dbcsCodePage) {
  562. unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
  563. // If ch is not a trail byte then pos is valid intercharacter position
  564. if (UTF8IsTrailByte(ch)) {
  565. int startUTF = pos;
  566. int endUTF = pos;
  567. if (InGoodUTF8(pos, startUTF, endUTF)) {
  568. // ch is a trail byte within a UTF-8 character
  569. if (moveDir > 0)
  570. pos = endUTF;
  571. else
  572. pos = startUTF;
  573. }
  574. // Else invalid UTF-8 so return position of isolated trail byte
  575. }
  576. } else {
  577. // Anchor DBCS calculations at start of line because start of line can
  578. // not be a DBCS trail byte.
  579. int posStartLine = LineStart(LineFromPosition(pos));
  580. if (pos == posStartLine)
  581. return pos;
  582. // Step back until a non-lead-byte is found.
  583. int posCheck = pos;
  584. while ((posCheck > posStartLine) && IsDBCSLeadByte(cb.CharAt(posCheck-1)))
  585. posCheck--;
  586. // Check from known start of character.
  587. while (posCheck < pos) {
  588. int mbsize = IsDBCSLeadByte(cb.CharAt(posCheck)) ? 2 : 1;
  589. if (posCheck + mbsize == pos) {
  590. return pos;
  591. } else if (posCheck + mbsize > pos) {
  592. if (moveDir > 0) {
  593. return posCheck + mbsize;
  594. } else {
  595. return posCheck;
  596. }
  597. }
  598. posCheck += mbsize;
  599. }
  600. }
  601. }
  602. return pos;
  603. }
  604. // NextPosition moves between valid positions - it can not handle a position in the middle of a
  605. // multi-byte character. It is used to iterate through text more efficiently than MovePositionOutsideChar.
  606. // A \r\n pair is treated as two characters.
  607. int Document::NextPosition(int pos, int moveDir) const {
  608. // If out of range, just return minimum/maximum value.
  609. int increment = (moveDir > 0) ? 1 : -1;
  610. if (pos + increment <= 0)
  611. return 0;
  612. if (pos + increment >= Length())
  613. return Length();
  614. if (dbcsCodePage) {
  615. if (SC_CP_UTF8 == dbcsCodePage) {
  616. if (increment == 1) {
  617. // Simple forward movement case so can avoid some checks
  618. const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(pos));
  619. if (UTF8IsAscii(leadByte)) {
  620. // Single byte character or invalid
  621. pos++;
  622. } else {
  623. const int widthCharBytes = UTF8BytesOfLead[leadByte];
  624. char charBytes[UTF8MaxBytes] = {static_cast<char>(leadByte),0,0,0};
  625. for (int b=1; b<widthCharBytes; b++)
  626. charBytes[b] = cb.CharAt(static_cast<int>(pos+b));
  627. int utf8status = UTF8Classify(reinterpret_cast<const unsigned char *>(charBytes), widthCharBytes);
  628. if (utf8status & UTF8MaskInvalid)
  629. pos++;
  630. else
  631. pos += utf8status & UTF8MaskWidth;
  632. }
  633. } else {
  634. // Examine byte before position
  635. pos--;
  636. unsigned char ch = static_cast<unsigned char>(cb.CharAt(pos));
  637. // If ch is not a trail byte then pos is valid intercharacter position
  638. if (UTF8IsTrailByte(ch)) {
  639. // If ch is a trail byte in a valid UTF-8 character then return start of character
  640. int startUTF = pos;
  641. int endUTF = pos;
  642. if (InGoodUTF8(pos, startUTF, endUTF)) {
  643. pos = startUTF;
  644. }
  645. // Else invalid UTF-8 so return position of isolated trail byte
  646. }
  647. }
  648. } else {
  649. if (moveDir > 0) {
  650. int mbsize = IsDBCSLeadByte(cb.CharAt(pos)) ? 2 : 1;
  651. pos += mbsize;
  652. if (pos > Length())
  653. pos = Length();
  654. } else {
  655. // Anchor DBCS calculations at start of line because start of line can
  656. // not be a DBCS trail byte.
  657. int posStartLine = LineStart(LineFromPosition(pos));
  658. // See http://msdn.microsoft.com/en-us/library/cc194792%28v=MSDN.10%29.aspx
  659. // http://msdn.microsoft.com/en-us/library/cc194790.aspx
  660. if ((pos - 1) <= posStartLine) {
  661. return pos - 1;
  662. } else if (IsDBCSLeadByte(cb.CharAt(pos - 1))) {
  663. // Must actually be trail byte
  664. return pos - 2;
  665. } else {
  666. // Otherwise, step back until a non-lead-byte is found.
  667. int posTemp = pos - 1;
  668. while (posStartLine <= --posTemp && IsDBCSLeadByte(cb.CharAt(posTemp)))
  669. ;
  670. // Now posTemp+1 must point to the beginning of a character,
  671. // so figure out whether we went back an even or an odd
  672. // number of bytes and go back 1 or 2 bytes, respectively.
  673. return (pos - 1 - ((pos - posTemp) & 1));
  674. }
  675. }
  676. }
  677. } else {
  678. pos += increment;
  679. }
  680. return pos;
  681. }
  682. bool Document::NextCharacter(int &pos, int moveDir) const {
  683. // Returns true if pos changed
  684. int posNext = NextPosition(pos, moveDir);
  685. if (posNext == pos) {
  686. return false;
  687. } else {
  688. pos = posNext;
  689. return true;
  690. }
  691. }
  692. // Return -1 on out-of-bounds
  693. int SCI_METHOD Document::GetRelativePosition(int positionStart, int characterOffset) const {
  694. int pos = positionStart;
  695. if (dbcsCodePage) {
  696. const int increment = (characterOffset > 0) ? 1 : -1;
  697. while (characterOffset != 0) {
  698. const int posNext = NextPosition(pos, increment);
  699. if (posNext == pos)
  700. return INVALID_POSITION;
  701. pos = posNext;
  702. characterOffset -= increment;
  703. }
  704. } else {
  705. pos = positionStart + characterOffset;
  706. if ((pos < 0) || (pos > Length()))
  707. return INVALID_POSITION;
  708. }
  709. return pos;
  710. }
  711. int Document::GetRelativePositionUTF16(int positionStart, int characterOffset) const {
  712. int pos = positionStart;
  713. if (dbcsCodePage) {
  714. const int increment = (characterOffset > 0) ? 1 : -1;
  715. while (characterOffset != 0) {
  716. const int posNext = NextPosition(pos, increment);
  717. if (posNext == pos)
  718. return INVALID_POSITION;
  719. if (abs(pos-posNext) > 3) // 4 byte character = 2*UTF16.
  720. characterOffset -= increment;
  721. pos = posNext;
  722. characterOffset -= increment;
  723. }
  724. } else {
  725. pos = positionStart + characterOffset;
  726. if ((pos < 0) || (pos > Length()))
  727. return INVALID_POSITION;
  728. }
  729. return pos;
  730. }
  731. int SCI_METHOD Document::GetCharacterAndWidth(int position, int *pWidth) const {
  732. int character;
  733. int bytesInCharacter = 1;
  734. if (dbcsCodePage) {
  735. const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(position));
  736. if (SC_CP_UTF8 == dbcsCodePage) {
  737. if (UTF8IsAscii(leadByte)) {
  738. // Single byte character or invalid
  739. character = leadByte;
  740. } else {
  741. const int widthCharBytes = UTF8BytesOfLead[leadByte];
  742. unsigned char charBytes[UTF8MaxBytes] = {leadByte,0,0,0};
  743. for (int b=1; b<widthCharBytes; b++)
  744. charBytes[b] = static_cast<unsigned char>(cb.CharAt(position+b));
  745. int utf8status = UTF8Classify(charBytes, widthCharBytes);
  746. if (utf8status & UTF8MaskInvalid) {
  747. // Report as singleton surrogate values which are invalid Unicode
  748. character = 0xDC80 + leadByte;
  749. } else {
  750. bytesInCharacter = utf8status & UTF8MaskWidth;
  751. character = UnicodeFromUTF8(charBytes);
  752. }
  753. }
  754. } else {
  755. if (IsDBCSLeadByte(leadByte)) {
  756. bytesInCharacter = 2;
  757. character = (leadByte << 8) | static_cast<unsigned char>(cb.CharAt(position+1));
  758. } else {
  759. character = leadByte;
  760. }
  761. }
  762. } else {
  763. character = cb.CharAt(position);
  764. }
  765. if (pWidth) {
  766. *pWidth = bytesInCharacter;
  767. }
  768. return character;
  769. }
  770. int SCI_METHOD Document::CodePage() const {
  771. return dbcsCodePage;
  772. }
  773. bool SCI_METHOD Document::IsDBCSLeadByte(char ch) const {
  774. // Byte ranges found in Wikipedia articles with relevant search strings in each case
  775. unsigned char uch = static_cast<unsigned char>(ch);
  776. switch (dbcsCodePage) {
  777. case 932:
  778. // Shift_jis
  779. return ((uch >= 0x81) && (uch <= 0x9F)) ||
  780. ((uch >= 0xE0) && (uch <= 0xFC));
  781. // Lead bytes F0 to FC may be a Microsoft addition.
  782. case 936:
  783. // GBK
  784. return (uch >= 0x81) && (uch <= 0xFE);
  785. case 949:
  786. // Korean Wansung KS C-5601-1987
  787. return (uch >= 0x81) && (uch <= 0xFE);
  788. case 950:
  789. // Big5
  790. return (uch >= 0x81) && (uch <= 0xFE);
  791. case 1361:
  792. // Korean Johab KS C-5601-1992
  793. return
  794. ((uch >= 0x84) && (uch <= 0xD3)) ||
  795. ((uch >= 0xD8) && (uch <= 0xDE)) ||
  796. ((uch >= 0xE0) && (uch <= 0xF9));
  797. }
  798. return false;
  799. }
  800. static inline bool IsSpaceOrTab(int ch) {
  801. return ch == ' ' || ch == '\t';
  802. }
  803. // Need to break text into segments near lengthSegment but taking into
  804. // account the encoding to not break inside a UTF-8 or DBCS character
  805. // and also trying to avoid breaking inside a pair of combining characters.
  806. // The segment length must always be long enough (more than 4 bytes)
  807. // so that there will be at least one whole character to make a segment.
  808. // For UTF-8, text must consist only of valid whole characters.
  809. // In preference order from best to worst:
  810. // 1) Break after space
  811. // 2) Break before punctuation
  812. // 3) Break after whole character
  813. int Document::SafeSegment(const char *text, int length, int lengthSegment) const {
  814. if (length <= lengthSegment)
  815. return length;
  816. int lastSpaceBreak = -1;
  817. int lastPunctuationBreak = -1;
  818. int lastEncodingAllowedBreak = 0;
  819. for (int j=0; j < lengthSegment;) {
  820. unsigned char ch = static_cast<unsigned char>(text[j]);
  821. if (j > 0) {
  822. if (IsSpaceOrTab(text[j - 1]) && !IsSpaceOrTab(text[j])) {
  823. lastSpaceBreak = j;
  824. }
  825. if (ch < 'A') {
  826. lastPunctuationBreak = j;
  827. }
  828. }
  829. lastEncodingAllowedBreak = j;
  830. if (dbcsCodePage == SC_CP_UTF8) {
  831. j += UTF8BytesOfLead[ch];
  832. } else if (dbcsCodePage) {
  833. j += IsDBCSLeadByte(ch) ? 2 : 1;
  834. } else {
  835. j++;
  836. }
  837. }
  838. if (lastSpaceBreak >= 0) {
  839. return lastSpaceBreak;
  840. } else if (lastPunctuationBreak >= 0) {
  841. return lastPunctuationBreak;
  842. }
  843. return lastEncodingAllowedBreak;
  844. }
  845. EncodingFamily Document::CodePageFamily() const {
  846. if (SC_CP_UTF8 == dbcsCodePage)
  847. return efUnicode;
  848. else if (dbcsCodePage)
  849. return efDBCS;
  850. else
  851. return efEightBit;
  852. }
  853. void Document::ModifiedAt(int pos) {
  854. if (endStyled > pos)
  855. endStyled = pos;
  856. }
  857. void Document::CheckReadOnly() {
  858. if (cb.IsReadOnly() && enteredReadOnlyCount == 0) {
  859. enteredReadOnlyCount++;
  860. NotifyModifyAttempt();
  861. enteredReadOnlyCount--;
  862. }
  863. }
  864. // Document only modified by gateways DeleteChars, InsertString, Undo, Redo, and SetStyleAt.
  865. // SetStyleAt does not change the persistent state of a document
  866. bool Document::DeleteChars(int pos, int len) {
  867. if (pos < 0)
  868. return false;
  869. if (len <= 0)
  870. return false;
  871. if ((pos + len) > Length())
  872. return false;
  873. CheckReadOnly();
  874. if (enteredModification != 0) {
  875. return false;
  876. } else {
  877. enteredModification++;
  878. if (!cb.IsReadOnly()) {
  879. NotifyModified(
  880. DocModification(
  881. SC_MOD_BEFOREDELETE | SC_PERFORMED_USER,
  882. pos, len,
  883. 0, 0));
  884. int prevLinesTotal = LinesTotal();
  885. bool startSavePoint = cb.IsSavePoint();
  886. bool startSequence = false;
  887. const char *text = cb.DeleteChars(pos, len, startSequence);
  888. if (startSavePoint && cb.IsCollectingUndo())
  889. NotifySavePoint(!startSavePoint);
  890. if ((pos < Length()) || (pos == 0))
  891. ModifiedAt(pos);
  892. else
  893. ModifiedAt(pos-1);
  894. NotifyModified(
  895. DocModification(
  896. SC_MOD_DELETETEXT | SC_PERFORMED_USER | (startSequence?SC_STARTACTION:0),
  897. pos, len,
  898. LinesTotal() - prevLinesTotal, text));
  899. }
  900. enteredModification--;
  901. }
  902. return !cb.IsReadOnly();
  903. }
  904. /**
  905. * Insert a string with a length.
  906. */
  907. int Document::InsertString(int position, const char *s, int insertLength) {
  908. if (insertLength <= 0) {
  909. return 0;
  910. }
  911. CheckReadOnly(); // Application may change read only state here
  912. if (cb.IsReadOnly()) {
  913. return 0;
  914. }
  915. if (enteredModification != 0) {
  916. return 0;
  917. }
  918. enteredModification++;
  919. insertionSet = false;
  920. insertion.clear();
  921. NotifyModified(
  922. DocModification(
  923. SC_MOD_INSERTCHECK,
  924. position, insertLength,
  925. 0, s));
  926. if (insertionSet) {
  927. s = insertion.c_str();
  928. insertLength = static_cast<int>(insertion.length());
  929. }
  930. NotifyModified(
  931. DocModification(
  932. SC_MOD_BEFOREINSERT | SC_PERFORMED_USER,
  933. position, insertLength,
  934. 0, s));
  935. int prevLinesTotal = LinesTotal();
  936. bool startSavePoint = cb.IsSavePoint();
  937. bool startSequence = false;
  938. const char *text = cb.InsertString(position, s, insertLength, startSequence);
  939. if (startSavePoint && cb.IsCollectingUndo())
  940. NotifySavePoint(!startSavePoint);
  941. ModifiedAt(position);
  942. NotifyModified(
  943. DocModification(
  944. SC_MOD_INSERTTEXT | SC_PERFORMED_USER | (startSequence?SC_STARTACTION:0),
  945. position, insertLength,
  946. LinesTotal() - prevLinesTotal, text));
  947. if (insertionSet) { // Free memory as could be large
  948. std::string().swap(insertion);
  949. }
  950. enteredModification--;
  951. return insertLength;
  952. }
  953. void Document::ChangeInsertion(const char *s, int length) {
  954. insertionSet = true;
  955. insertion.assign(s, length);
  956. }
  957. int SCI_METHOD Document::AddData(char *data, int length) {
  958. try {
  959. int position = Length();
  960. InsertString(position, data, length);
  961. } catch (std::bad_alloc &) {
  962. return SC_STATUS_BADALLOC;
  963. } catch (...) {
  964. return SC_STATUS_FAILURE;
  965. }
  966. return 0;
  967. }
  968. void * SCI_METHOD Document::ConvertToDocument() {
  969. return this;
  970. }
  971. int Document::Undo() {
  972. int newPos = -1;
  973. CheckReadOnly();
  974. if ((enteredModification == 0) && (cb.IsCollectingUndo())) {
  975. enteredModification++;
  976. if (!cb.IsReadOnly()) {
  977. bool startSavePoint = cb.IsSavePoint();
  978. bool multiLine = false;
  979. int steps = cb.StartUndo();
  980. //Platform::DebugPrintf("Steps=%d\n", steps);
  981. int coalescedRemovePos = -1;
  982. int coalescedRemoveLen = 0;
  983. int prevRemoveActionPos = -1;
  984. int prevRemoveActionLen = 0;
  985. for (int step = 0; step < steps; step++) {
  986. const int prevLinesTotal = LinesTotal();
  987. const Action &action = cb.GetUndoStep();
  988. if (action.at == removeAction) {
  989. NotifyModified(DocModification(
  990. SC_MOD_BEFOREINSERT | SC_PERFORMED_UNDO, action));
  991. } else if (action.at == containerAction) {
  992. DocModification dm(SC_MOD_CONTAINER | SC_PERFORMED_UNDO);
  993. dm.token = action.position;
  994. NotifyModified(dm);
  995. if (!action.mayCoalesce) {
  996. coalescedRemovePos = -1;
  997. coalescedRemoveLen = 0;
  998. prevRemoveActionPos = -1;
  999. prevRemoveActionLen = 0;
  1000. }
  1001. } else {
  1002. NotifyModified(DocModification(
  1003. SC_MOD_BEFOREDELETE | SC_PERFORMED_UNDO, action));
  1004. }
  1005. cb.PerformUndoStep();
  1006. if (action.at != containerAction) {
  1007. ModifiedAt(action.position);
  1008. newPos = action.position;
  1009. }
  1010. int modFlags = SC_PERFORMED_UNDO;
  1011. // With undo, an insertion action becomes a deletion notification
  1012. if (action.at == removeAction) {
  1013. newPos += action.lenData;
  1014. modFlags |= SC_MOD_INSERTTEXT;
  1015. if ((coalescedRemoveLen > 0) &&
  1016. (action.position == prevRemoveActionPos || action.position == (prevRemoveActionPos + prevRemoveActionLen))) {
  1017. coalescedRemoveLen += action.lenData;
  1018. newPos = coalescedRemovePos + coalescedRemoveLen;
  1019. } else {
  1020. coalescedRemovePos = action.position;
  1021. coalescedRemoveLen = action.lenData;
  1022. }
  1023. prevRemoveActionPos = action.position;
  1024. prevRemoveActionLen = action.lenData;
  1025. } else if (action.at == insertAction) {
  1026. modFlags |= SC_MOD_DELETETEXT;
  1027. coalescedRemovePos = -1;
  1028. coalescedRemoveLen = 0;
  1029. prevRemoveActionPos = -1;
  1030. prevRemoveActionLen = 0;
  1031. }
  1032. if (steps > 1)
  1033. modFlags |= SC_MULTISTEPUNDOREDO;
  1034. const int linesAdded = LinesTotal() - prevLinesTotal;
  1035. if (linesAdded != 0)
  1036. multiLine = true;
  1037. if (step == steps - 1) {
  1038. modFlags |= SC_LASTSTEPINUNDOREDO;
  1039. if (multiLine)
  1040. modFlags |= SC_MULTILINEUNDOREDO;
  1041. }
  1042. NotifyModified(DocModification(modFlags, action.position, action.lenData,
  1043. linesAdded, action.data));
  1044. }
  1045. bool endSavePoint = cb.IsSavePoint();
  1046. if (startSavePoint != endSavePoint)
  1047. NotifySavePoint(endSavePoint);
  1048. }
  1049. enteredModification--;
  1050. }
  1051. return newPos;
  1052. }
  1053. int Document::Redo() {
  1054. int newPos = -1;
  1055. CheckReadOnly();
  1056. if ((enteredModification == 0) && (cb.IsCollectingUndo())) {
  1057. enteredModification++;
  1058. if (!cb.IsReadOnly()) {
  1059. bool startSavePoint = cb.IsSavePoint();
  1060. bool multiLine = false;
  1061. int steps = cb.StartRedo();
  1062. for (int step = 0; step < steps; step++) {
  1063. const int prevLinesTotal = LinesTotal();
  1064. const Action &action = cb.GetRedoStep();
  1065. if (action.at == insertAction) {
  1066. NotifyModified(DocModification(
  1067. SC_MOD_BEFOREINSERT | SC_PERFORMED_REDO, action));
  1068. } else if (action.at == containerAction) {
  1069. DocModification dm(SC_MOD_CONTAINER | SC_PERFORMED_REDO);
  1070. dm.token = action.position;
  1071. NotifyModified(dm);
  1072. } else {
  1073. NotifyModified(DocModification(
  1074. SC_MOD_BEFOREDELETE | SC_PERFORMED_REDO, action));
  1075. }
  1076. cb.PerformRedoStep();
  1077. if (action.at != containerAction) {
  1078. ModifiedAt(action.position);
  1079. newPos = action.position;
  1080. }
  1081. int modFlags = SC_PERFORMED_REDO;
  1082. if (action.at == insertAction) {
  1083. newPos += action.lenData;
  1084. modFlags |= SC_MOD_INSERTTEXT;
  1085. } else if (action.at == removeAction) {
  1086. modFlags |= SC_MOD_DELETETEXT;
  1087. }
  1088. if (steps > 1)
  1089. modFlags |= SC_MULTISTEPUNDOREDO;
  1090. const int linesAdded = LinesTotal() - prevLinesTotal;
  1091. if (linesAdded != 0)
  1092. multiLine = true;
  1093. if (step == steps - 1) {
  1094. modFlags |= SC_LASTSTEPINUNDOREDO;
  1095. if (multiLine)
  1096. modFlags |= SC_MULTILINEUNDOREDO;
  1097. }
  1098. NotifyModified(
  1099. DocModification(modFlags, action.position, action.lenData,
  1100. linesAdded, action.data));
  1101. }
  1102. bool endSavePoint = cb.IsSavePoint();
  1103. if (startSavePoint != endSavePoint)
  1104. NotifySavePoint(endSavePoint);
  1105. }
  1106. enteredModification--;
  1107. }
  1108. return newPos;
  1109. }
  1110. void Document::DelChar(int pos) {
  1111. DeleteChars(pos, LenChar(pos));
  1112. }
  1113. void Document::DelCharBack(int pos) {
  1114. if (pos <= 0) {
  1115. return;
  1116. } else if (IsCrLf(pos - 2)) {
  1117. DeleteChars(pos - 2, 2);
  1118. } else if (dbcsCodePage) {
  1119. int startChar = NextPosition(pos, -1);
  1120. DeleteChars(startChar, pos - startChar);
  1121. } else {
  1122. DeleteChars(pos - 1, 1);
  1123. }
  1124. }
  1125. static int NextTab(int pos, int tabSize) {
  1126. return ((pos / tabSize) + 1) * tabSize;
  1127. }
  1128. static std::string CreateIndentation(int indent, int tabSize, bool insertSpaces) {
  1129. std::string indentation;
  1130. if (!insertSpaces) {
  1131. while (indent >= tabSize) {
  1132. indentation += '\t';
  1133. indent -= tabSize;
  1134. }
  1135. }
  1136. while (indent > 0) {
  1137. indentation += ' ';
  1138. indent--;
  1139. }
  1140. return indentation;
  1141. }
  1142. int SCI_METHOD Document::GetLineIndentation(int line) {
  1143. int indent = 0;
  1144. if ((line >= 0) && (line < LinesTotal())) {
  1145. int lineStart = LineStart(line);
  1146. int length = Length();
  1147. for (int i = lineStart; i < length; i++) {
  1148. char ch = cb.CharAt(i);
  1149. if (ch == ' ')
  1150. indent++;
  1151. else if (ch == '\t')
  1152. indent = NextTab(indent, tabInChars);
  1153. else
  1154. return indent;
  1155. }
  1156. }
  1157. return indent;
  1158. }
  1159. int Document::SetLineIndentation(int line, int indent) {
  1160. int indentOfLine = GetLineIndentation(line);
  1161. if (indent < 0)
  1162. indent = 0;
  1163. if (indent != indentOfLine) {
  1164. std::string linebuf = CreateIndentation(indent, tabInChars, !useTabs);
  1165. int thisLineStart = LineStart(line);
  1166. int indentPos = GetLineIndentPosition(line);
  1167. UndoGroup ug(this);
  1168. DeleteChars(thisLineStart, indentPos - thisLineStart);
  1169. return thisLineStart + InsertString(thisLineStart, linebuf.c_str(),
  1170. static_cast<int>(linebuf.length()));
  1171. } else {
  1172. return GetLineIndentPosition(line);
  1173. }
  1174. }
  1175. int Document::GetLineIndentPosition(int line) const {
  1176. if (line < 0)
  1177. return 0;
  1178. int pos = LineStart(line);
  1179. int length = Length();
  1180. while ((pos < length) && IsSpaceOrTab(cb.CharAt(pos))) {
  1181. pos++;
  1182. }
  1183. return pos;
  1184. }
  1185. int Document::GetColumn(int pos) {
  1186. int column = 0;
  1187. int line = LineFromPosition(pos);
  1188. if ((line >= 0) && (line < LinesTotal())) {
  1189. for (int i = LineStart(line); i < pos;) {
  1190. char ch = cb.CharAt(i);
  1191. if (ch == '\t') {
  1192. column = NextTab(column, tabInChars);
  1193. i++;
  1194. } else if (ch == '\r') {
  1195. return column;
  1196. } else if (ch == '\n') {
  1197. return column;
  1198. } else if (i >= Length()) {
  1199. return column;
  1200. } else {
  1201. column++;
  1202. i = NextPosition(i, 1);
  1203. }
  1204. }
  1205. }
  1206. return column;
  1207. }
  1208. int Document::CountCharacters(int startPos, int endPos) const {
  1209. startPos = MovePositionOutsideChar(startPos, 1, false);
  1210. endPos = MovePositionOutsideChar(endPos, -1, false);
  1211. int count = 0;
  1212. int i = startPos;
  1213. while (i < endPos) {
  1214. count++;
  1215. if (IsCrLf(i))
  1216. i++;
  1217. i = NextPosition(i, 1);
  1218. }
  1219. return count;
  1220. }
  1221. int Document::CountUTF16(int startPos, int endPos) const {
  1222. startPos = MovePositionOutsideChar(startPos, 1, false);
  1223. endPos = MovePositionOutsideChar(endPos, -1, false);
  1224. int count = 0;
  1225. int i = startPos;
  1226. while (i < endPos) {
  1227. count++;
  1228. const int next = NextPosition(i, 1);
  1229. if ((next - i) > 3)
  1230. count++;
  1231. i = next;
  1232. }
  1233. return count;
  1234. }
  1235. int Document::FindColumn(int line, int column) {
  1236. int position = LineStart(line);
  1237. if ((line >= 0) && (line < LinesTotal())) {
  1238. int columnCurrent = 0;
  1239. while ((columnCurrent < column) && (position < Length())) {
  1240. char ch = cb.CharAt(position);
  1241. if (ch == '\t') {
  1242. columnCurrent = NextTab(columnCurrent, tabInChars);
  1243. if (columnCurrent > column)
  1244. return position;
  1245. position++;
  1246. } else if (ch == '\r') {
  1247. return position;
  1248. } else if (ch == '\n') {
  1249. return position;
  1250. } else {
  1251. columnCurrent++;
  1252. position = NextPosition(position, 1);
  1253. }
  1254. }
  1255. }
  1256. return position;
  1257. }
  1258. void Document::Indent(bool forwards, int lineBottom, int lineTop) {
  1259. // Dedent - suck white space off the front of the line to dedent by equivalent of a tab
  1260. for (int line = lineBottom; line >= lineTop; line--) {
  1261. int indentOfLine = GetLineIndentation(line);
  1262. if (forwards) {
  1263. if (LineStart(line) < LineEnd(line)) {
  1264. SetLineIndentation(line, indentOfLine + IndentSize());
  1265. }
  1266. } else {
  1267. SetLineIndentation(line, indentOfLine - IndentSize());
  1268. }
  1269. }
  1270. }
  1271. // Convert line endings for a piece of text to a particular mode.
  1272. // Stop at len or when a NUL is found.
  1273. std::string Document::TransformLineEnds(const char *s, size_t len, int eolModeWanted) {
  1274. std::string dest;
  1275. for (size_t i = 0; (i < len) && (s[i]); i++) {
  1276. if (s[i] == '\n' || s[i] == '\r') {
  1277. if (eolModeWanted == SC_EOL_CR) {
  1278. dest.push_back('\r');
  1279. } else if (eolModeWanted == SC_EOL_LF) {
  1280. dest.push_back('\n');
  1281. } else { // eolModeWanted == SC_EOL_CRLF
  1282. dest.push_back('\r');
  1283. dest.push_back('\n');
  1284. }
  1285. if ((s[i] == '\r') && (i+1 < len) && (s[i+1] == '\n')) {
  1286. i++;
  1287. }
  1288. } else {
  1289. dest.push_back(s[i]);
  1290. }
  1291. }
  1292. return dest;
  1293. }
  1294. void Document::ConvertLineEnds(int eolModeSet) {
  1295. UndoGroup ug(this);
  1296. for (int pos = 0; pos < Length(); pos++) {
  1297. if (cb.CharAt(pos) == '\r') {
  1298. if (cb.CharAt(pos + 1) == '\n') {
  1299. // CRLF
  1300. if (eolModeSet == SC_EOL_CR) {
  1301. DeleteChars(pos + 1, 1); // Delete the LF
  1302. } else if (eolModeSet == SC_EOL_LF) {
  1303. DeleteChars(pos, 1); // Delete the CR
  1304. } else {
  1305. pos++;
  1306. }
  1307. } else {
  1308. // CR
  1309. if (eolModeSet == SC_EOL_CRLF) {
  1310. pos += InsertString(pos + 1, "\n", 1); // Insert LF
  1311. } else if (eolModeSet == SC_EOL_LF) {
  1312. pos += InsertString(pos, "\n", 1); // Insert LF
  1313. DeleteChars(pos, 1); // Delete CR
  1314. pos--;
  1315. }
  1316. }
  1317. } else if (cb.CharAt(pos) == '\n') {
  1318. // LF
  1319. if (eolModeSet == SC_EOL_CRLF) {
  1320. pos += InsertString(pos, "\r", 1); // Insert CR
  1321. } else if (eolModeSet == SC_EOL_CR) {
  1322. pos += InsertString(pos, "\r", 1); // Insert CR
  1323. DeleteChars(pos, 1); // Delete LF
  1324. pos--;
  1325. }
  1326. }
  1327. }
  1328. }
  1329. bool Document::IsWhiteLine(int line) const {
  1330. int currentChar = LineStart(line);
  1331. int endLine = LineEnd(line);
  1332. while (currentChar < endLine) {
  1333. if (cb.CharAt(currentChar) != ' ' && cb.CharAt(currentChar) != '\t') {
  1334. return false;
  1335. }
  1336. ++currentChar;
  1337. }
  1338. return true;
  1339. }
  1340. int Document::ParaUp(int pos) const {
  1341. int line = LineFromPosition(pos);
  1342. line--;
  1343. while (line >= 0 && IsWhiteLine(line)) { // skip empty lines
  1344. line--;
  1345. }
  1346. while (line >= 0 && !IsWhiteLine(line)) { // skip non-empty lines
  1347. line--;
  1348. }
  1349. line++;
  1350. return LineStart(line);
  1351. }
  1352. int Document::ParaDown(int pos) const {
  1353. int line = LineFromPosition(pos);
  1354. while (line < LinesTotal() && !IsWhiteLine(line)) { // skip non-empty lines
  1355. line++;
  1356. }
  1357. while (line < LinesTotal() && IsWhiteLine(line)) { // skip empty lines
  1358. line++;
  1359. }
  1360. if (line < LinesTotal())
  1361. return LineStart(line);
  1362. else // end of a document
  1363. return LineEnd(line-1);
  1364. }
  1365. CharClassify::cc Document::WordCharClass(unsigned char ch) const {
  1366. if ((SC_CP_UTF8 == dbcsCodePage) && (!UTF8IsAscii(ch)))
  1367. return CharClassify::ccWord;
  1368. return charClass.GetClass(ch);
  1369. }
  1370. /**
  1371. * Used by commmands that want to select whole words.
  1372. * Finds the start of word at pos when delta < 0 or the end of the word when delta >= 0.
  1373. */
  1374. int Document::ExtendWordSelect(int pos, int delta, bool onlyWordCharacters) {
  1375. CharClassify::cc ccStart = CharClassify::ccWord;
  1376. if (delta < 0) {
  1377. if (!onlyWordCharacters)
  1378. ccStart = WordCharClass(cb.CharAt(pos-1));
  1379. while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == ccStart))
  1380. pos--;
  1381. } else {
  1382. if (!onlyWordCharacters && pos < Length())
  1383. ccStart = WordCharClass(cb.CharAt(pos));
  1384. while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == ccStart))
  1385. pos++;
  1386. }
  1387. return MovePositionOutsideChar(pos, delta, true);
  1388. }
  1389. /**
  1390. * Find the start of the next word in either a forward (delta >= 0) or backwards direction
  1391. * (delta < 0).
  1392. * This is looking for a transition between character classes although there is also some
  1393. * additional movement to transit white space.
  1394. * Used by cursor movement by word commands.
  1395. */
  1396. int Document::NextWordStart(int pos, int delta) {
  1397. if (delta < 0) {
  1398. while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == CharClassify::ccSpace))
  1399. pos--;
  1400. if (pos > 0) {
  1401. CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos-1));
  1402. while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == ccStart)) {
  1403. pos--;
  1404. }
  1405. }
  1406. } else {
  1407. CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos));
  1408. while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == ccStart))
  1409. pos++;
  1410. while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == CharClassify::ccSpace))
  1411. pos++;
  1412. }
  1413. return pos;
  1414. }
  1415. /**
  1416. * Find the end of the next word in either a forward (delta >= 0) or backwards direction
  1417. * (delta < 0).
  1418. * This is looking for a transition between character classes although there is also some
  1419. * additional movement to transit white space.
  1420. * Used by cursor movement by word commands.
  1421. */
  1422. int Document::NextWordEnd(int pos, int delta) {
  1423. if (delta < 0) {
  1424. if (pos > 0) {
  1425. CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos-1));
  1426. if (ccStart != CharClassify::ccSpace) {
  1427. while (pos > 0 && WordCharClass(cb.CharAt(pos - 1)) == ccStart) {
  1428. pos--;
  1429. }
  1430. }
  1431. while (pos > 0 && WordCharClass(cb.CharAt(pos - 1)) == CharClassify::ccSpace) {
  1432. pos--;
  1433. }
  1434. }
  1435. } else {
  1436. while (pos < Length() && WordCharClass(cb.CharAt(pos)) == CharClassify::ccSpace) {
  1437. pos++;
  1438. }
  1439. if (pos < Length()) {
  1440. CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos));
  1441. while (pos < Length() && WordCharClass(cb.CharAt(pos)) == ccStart) {
  1442. pos++;
  1443. }
  1444. }
  1445. }
  1446. return pos;
  1447. }
  1448. /**
  1449. * Check that the character at the given position is a word or punctuation character and that
  1450. * the previous character is of a different character class.
  1451. */
  1452. bool Document::IsWordStartAt(int pos) const {
  1453. if (pos > 0) {
  1454. CharClassify::cc ccPos = WordCharClass(CharAt(pos));
  1455. return (ccPos == CharClassify::ccWord || ccPos == CharClassify::ccPunctuation) &&
  1456. (ccPos != WordCharClass(CharAt(pos - 1)));
  1457. }
  1458. return true;
  1459. }
  1460. /**
  1461. * Check that the character at the given position is a word or punctuation character and that
  1462. * the next character is of a different character class.
  1463. */
  1464. bool Document::IsWordEndAt(int pos) const {
  1465. if (pos < Length()) {
  1466. CharClassify::cc ccPrev = WordCharClass(CharAt(pos-1));
  1467. return (ccPrev == CharClassify::ccWord || ccPrev == CharClassify::ccPunctuation) &&
  1468. (ccPrev != WordCharClass(CharAt(pos)));
  1469. }
  1470. return true;
  1471. }
  1472. /**
  1473. * Check that the given range is has transitions between character classes at both
  1474. * ends and where the characters on the inside are word or punctuation characters.
  1475. */
  1476. bool Document::IsWordAt(int start, int end) const {
  1477. return (start < end) && IsWordStartAt(start) && IsWordEndAt(end);
  1478. }
  1479. bool Document::MatchesWordOptions(bool word, bool wordStart, int pos, int length) const {
  1480. return (!word && !wordStart) ||
  1481. (word && IsWordAt(pos, pos + length)) ||
  1482. (wordStart && IsWordStartAt(pos));
  1483. }
  1484. bool Document::HasCaseFolder(void) const {
  1485. return pcf != 0;
  1486. }
  1487. void Document::SetCaseFolder(CaseFolder *pcf_) {
  1488. delete pcf;
  1489. pcf = pcf_;
  1490. }
  1491. Document::CharacterExtracted Document::ExtractCharacter(int position) const {
  1492. const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(position));
  1493. if (UTF8IsAscii(leadByte)) {
  1494. // Common case: ASCII character
  1495. return CharacterExtracted(leadByte, 1);
  1496. }
  1497. const int widthCharBytes = UTF8BytesOfLead[leadByte];
  1498. unsigned char charBytes[UTF8MaxBytes] = { leadByte, 0, 0, 0 };
  1499. for (int b=1; b<widthCharBytes; b++)
  1500. charBytes[b] = static_cast<unsigned char>(cb.CharAt(position + b));
  1501. int utf8status = UTF8Classify(charBytes, widthCharBytes);
  1502. if (utf8status & UTF8MaskInvalid) {
  1503. // Treat as invalid and use up just one byte
  1504. return CharacterExtracted(unicodeReplacementChar, 1);
  1505. } else {
  1506. return CharacterExtracted(UnicodeFromUTF8(charBytes), utf8status & UTF8MaskWidth);
  1507. }
  1508. }
  1509. /**
  1510. * Find text in document, supporting both forward and backward
  1511. * searches (just pass minPos > maxPos to do a backward search)
  1512. * Has not been tested with backwards DBCS searches yet.
  1513. */
  1514. long Document::FindText(int minPos, int maxPos, const char *search,
  1515. int flags, int *length) {
  1516. if (*length <= 0)
  1517. return minPos;
  1518. const bool caseSensitive = (flags & SCFIND_MATCHCASE) != 0;
  1519. const bool word = (flags & SCFIND_WHOLEWORD) != 0;
  1520. const bool wordStart = (flags & SCFIND_WORDSTART) != 0;
  1521. const bool regExp = (flags & SCFIND_REGEXP) != 0;
  1522. if (regExp) {
  1523. if (!regex)
  1524. regex = CreateRegexSearch(&charClass);
  1525. return regex->FindText(this, minPos, maxPos, search, caseSensitive, word, wordStart, flags, length);
  1526. } else {
  1527. const bool forward = minPos <= maxPos;
  1528. const int increment = forward ? 1 : -1;
  1529. // Range endpoints should not be inside DBCS characters, but just in case, move them.
  1530. const int startPos = MovePositionOutsideChar(minPos, increment, false);
  1531. const int endPos = MovePositionOutsideChar(maxPos, increment, false);
  1532. // Compute actual search ranges needed
  1533. const int lengthFind = *length;
  1534. //Platform::DebugPrintf("Find %d %d %s %d\n", startPos, endPos, ft->lpstrText, lengthFind);
  1535. const int limitPos = Platform::Maximum(startPos, endPos);
  1536. int pos = startPos;
  1537. if (!forward) {
  1538. // Back all of a character
  1539. pos = NextPosition(pos, increment);
  1540. }
  1541. if (caseSensitive) {
  1542. const int endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : endPos;
  1543. const char charStartSearch = search[0];
  1544. while (forward ? (pos < endSearch) : (pos >= endSearch)) {
  1545. if (CharAt(pos) == charStartSearch) {
  1546. bool found = (pos + lengthFind) <= limitPos;
  1547. for (int indexSearch = 1; (indexSearch < lengthFind) && found; indexSearch++) {
  1548. found = CharAt(pos + indexSearch) == search[indexSearch];
  1549. }
  1550. if (found && MatchesWordOptions(word, wordStart, pos, lengthFind)) {
  1551. return pos;
  1552. }
  1553. }
  1554. if (!NextCharacter(pos, increment))
  1555. break;
  1556. }
  1557. } else if (SC_CP_UTF8 == dbcsCodePage) {
  1558. const size_t maxFoldingExpansion = 4;
  1559. std::vector<char> searchThing(lengthFind * UTF8MaxBytes * maxFoldingExpansion + 1);
  1560. const int lenSearch = static_cast<int>(
  1561. pcf->Fold(&searchThing[0], searchThing.size(), search, lengthFind));
  1562. char bytes[UTF8MaxBytes + 1];
  1563. char folded[UTF8MaxBytes * maxFoldingExpansion + 1];
  1564. while (forward ? (pos < endPos) : (pos >= endPos)) {
  1565. int widthFirstCharacter = 0;
  1566. int posIndexDocument = pos;
  1567. int indexSearch = 0;
  1568. bool characterMatches = true;
  1569. for (;;) {
  1570. const unsigned char leadByte = static_cast<unsigned char>(cb.CharAt(posIndexDocument));
  1571. bytes[0] = leadByte;
  1572. int widthChar = 1;
  1573. if (!UTF8IsAscii(leadByte)) {
  1574. const int widthCharBytes = UTF8BytesOfLead[leadByte];
  1575. for (int b=1; b<widthCharBytes; b++) {
  1576. bytes[b] = cb.CharAt(posIndexDocument+b);
  1577. }
  1578. widthChar = UTF8Classify(reinterpret_cast<const unsigned char *>(bytes), widthCharBytes) & UTF8MaskWidth;
  1579. }
  1580. if (!widthFirstCharacter)
  1581. widthFirstCharacter = widthChar;
  1582. if ((posIndexDocument + widthChar) > limitPos)
  1583. break;
  1584. const int lenFlat = static_cast<int>(pcf->Fold(folded, sizeof(folded), bytes, widthChar));
  1585. folded[lenFlat] = 0;
  1586. // Does folded match the buffer
  1587. characterMatches = 0 == memcmp(folded, &searchThing[0] + indexSearch, lenFlat);
  1588. if (!characterMatches)
  1589. break;
  1590. posIndexDocument += widthChar;
  1591. indexSearch += lenFlat;
  1592. if (indexSearch >= lenSearch)
  1593. break;
  1594. }
  1595. if (characterMatches && (indexSearch == static_cast<int>(lenSearch))) {
  1596. if (MatchesWordOptions(word, wordStart, pos, posIndexDocument - pos)) {
  1597. *length = posIndexDocument - pos;
  1598. return pos;
  1599. }
  1600. }
  1601. if (forward) {
  1602. pos += widthFirstCharacter;
  1603. } else {
  1604. if (!NextCharacter(pos, increment))
  1605. break;
  1606. }
  1607. }
  1608. } else if (dbcsCodePage) {
  1609. const size_t maxBytesCharacter = 2;
  1610. const size_t maxFoldingExpansion = 4;
  1611. std::vector<char> searchThing(lengthFind * maxBytesCharacter * maxFoldingExpansion + 1);
  1612. const int lenSearch = static_cast<int>(
  1613. pcf->Fold(&searchThing[0], searchThing.size(), search, lengthFind));
  1614. while (forward ? (pos < endPos) : (pos >= endPos)) {
  1615. int indexDocument = 0;
  1616. int indexSearch = 0;
  1617. bool characterMatches = true;
  1618. while (characterMatches &&
  1619. ((pos + indexDocument) < limitPos) &&
  1620. (indexSearch < lenSearch)) {
  1621. char bytes[maxBytesCharacter + 1];
  1622. bytes[0] = cb.CharAt(pos + indexDocument);
  1623. const int widthChar = IsDBCSLeadByte(bytes[0]) ? 2 : 1;
  1624. if (widthChar == 2)
  1625. bytes[1] = cb.CharAt(pos + indexDocument + 1);
  1626. if ((pos + indexDocument + widthChar) > limitPos)
  1627. break;
  1628. char folded[maxBytesCharacter * maxFoldingExpansion + 1];
  1629. const int lenFlat = static_cast<int>(pcf->Fold(folded, sizeof(folded), bytes, widthChar));
  1630. folded[lenFlat] = 0;
  1631. // Does folded match the buffer
  1632. characterMatches = 0 == memcmp(folded, &searchThing[0] + indexSearch, lenFlat);
  1633. indexDocument += widthChar;
  1634. indexSearch += lenFlat;
  1635. }
  1636. if (characterMatches && (indexSearch == static_cast<int>(lenSearch))) {
  1637. if (MatchesWordOptions(word, wordStart, pos, indexDocument)) {
  1638. *length = indexDocument;
  1639. return pos;
  1640. }
  1641. }
  1642. if (!NextCharacter(pos, increment))
  1643. break;
  1644. }
  1645. } else {
  1646. const int endSearch = (startPos <= endPos) ? endPos - lengthFind + 1 : endPos;
  1647. std::vector<char> searchThing(lengthFind + 1);
  1648. pcf->Fold(&searchThing[0], searchThing.size(), search, lengthFind);
  1649. while (forward ? (pos < endSearch) : (pos >= endSearch)) {
  1650. bool found = (pos + lengthFind) <= limitPos;
  1651. for (int indexSearch = 0; (indexSearch < lengthFind) && found; indexSearch++) {
  1652. char ch = CharAt(pos + indexSearch);
  1653. char folded[2];
  1654. pcf->Fold(folded, sizeof(folded), &ch, 1);
  1655. found = folded[0] == searchThing[indexSearch];
  1656. }
  1657. if (found && MatchesWordOptions(word, wordStart, pos, lengthFind)) {
  1658. return pos;
  1659. }
  1660. if (!NextCharacter(pos, increment))
  1661. break;
  1662. }
  1663. }
  1664. }
  1665. //Platform::DebugPrintf("Not found\n");
  1666. return -1;
  1667. }
  1668. const char *Document::SubstituteByPosition(const char *text, int *length) {
  1669. if (regex)
  1670. return regex->SubstituteByPosition(this, text, length);
  1671. else
  1672. return 0;
  1673. }
  1674. int Document::LinesTotal() const {
  1675. return cb.Lines();
  1676. }
  1677. void Document::SetDefaultCharClasses(bool includeWordClass) {
  1678. charClass.SetDefaultCharClasses(includeWordClass);
  1679. }
  1680. void Document::SetCharClasses(const unsigned char *chars, CharClassify::cc newCharClass) {
  1681. charClass.SetCharClasses(chars, newCharClass);
  1682. }
  1683. int Document::GetCharsOfClass(CharClassify::cc characterClass, unsigned char *buffer) {
  1684. return charClass.GetCharsOfClass(characterClass, buffer);
  1685. }
  1686. void SCI_METHOD Document::StartStyling(int position, char) {
  1687. endStyled = position;
  1688. }
  1689. bool SCI_METHOD Document::SetStyleFor(int length, char style) {
  1690. if (enteredStyling != 0) {
  1691. return false;
  1692. } else {
  1693. enteredStyling++;
  1694. int prevEndStyled = endStyled;
  1695. if (cb.SetStyleFor(endStyled, length, style)) {
  1696. DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER,
  1697. prevEndStyled, length);
  1698. NotifyModified(mh);
  1699. }
  1700. endStyled += length;
  1701. enteredStyling--;
  1702. return true;
  1703. }
  1704. }
  1705. bool SCI_METHOD Document::SetStyles(int length, const char *styles) {
  1706. if (enteredStyling != 0) {
  1707. return false;
  1708. } else {
  1709. enteredStyling++;
  1710. bool didChange = false;
  1711. int startMod = 0;
  1712. int endMod = 0;
  1713. for (int iPos = 0; iPos < length; iPos++, endStyled++) {
  1714. PLATFORM_ASSERT(endStyled < Length());
  1715. if (cb.SetStyleAt(endStyled, styles[iPos])) {
  1716. if (!didChange) {
  1717. startMod = endStyled;
  1718. }
  1719. didChange = true;
  1720. endMod = endStyled;
  1721. }
  1722. }
  1723. if (didChange) {
  1724. DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER,
  1725. startMod, endMod - startMod + 1);
  1726. NotifyModified(mh);
  1727. }
  1728. enteredStyling--;
  1729. return true;
  1730. }
  1731. }
  1732. void Document::EnsureStyledTo(int pos) {
  1733. if ((enteredStyling == 0) && (pos > GetEndStyled())) {
  1734. IncrementStyleClock();
  1735. if (pli && !pli->UseContainerLexing()) {
  1736. int lineEndStyled = LineFromPosition(GetEndStyled());
  1737. int endStyledTo = LineStart(lineEndStyled);
  1738. pli->Colourise(endStyledTo, pos);
  1739. } else {
  1740. // Ask the watchers to style, and stop as soon as one responds.
  1741. for (std::vector<WatcherWithUserData>::iterator it = watchers.begin();
  1742. (pos > GetEndStyled()) && (it != watchers.end()); ++it) {
  1743. it->watcher->NotifyStyleNeeded(this, it->userData, pos);
  1744. }
  1745. }
  1746. }
  1747. }
  1748. void Document::LexerChanged() {
  1749. // Tell the watchers the lexer has changed.
  1750. for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
  1751. it->watcher->NotifyLexerChanged(this, it->userData);
  1752. }
  1753. }
  1754. int SCI_METHOD Document::SetLineState(int line, int state) {
  1755. int statePrevious = static_cast<LineState *>(perLineData[ldState])->SetLineState(line, state);
  1756. if (state != statePrevious) {
  1757. DocModification mh(SC_MOD_CHANGELINESTATE, LineStart(line), 0, 0, 0, line);
  1758. NotifyModified(mh);
  1759. }
  1760. return statePrevious;
  1761. }
  1762. int SCI_METHOD Document::GetLineState(int line) const {
  1763. return static_cast<LineState *>(perLineData[ldState])->GetLineState(line);
  1764. }
  1765. int Document::GetMaxLineState() {
  1766. return static_cast<LineState *>(perLineData[ldState])->GetMaxLineState();
  1767. }
  1768. void SCI_METHOD Document::ChangeLexerState(int start, int end) {
  1769. DocModification mh(SC_MOD_LEXERSTATE, start, end-start, 0, 0, 0);
  1770. NotifyModified(mh);
  1771. }
  1772. StyledText Document::MarginStyledText(int line) const {
  1773. LineAnnotation *pla = static_cast<LineAnnotation *>(perLineData[ldMargin]);
  1774. return StyledText(pla->Length(line), pla->Text(line),
  1775. pla->MultipleStyles(line), pla->Style(line), pla->Styles(line));
  1776. }
  1777. void Document::MarginSetText(int line, const char *text) {
  1778. static_cast<LineAnnotation *>(perLineData[ldMargin])->SetText(line, text);
  1779. DocModification mh(SC_MOD_CHANGEMARGIN, LineStart(line), 0, 0, 0, line);
  1780. NotifyModified(mh);
  1781. }
  1782. void Document::MarginSetStyle(int line, int style) {
  1783. static_cast<LineAnnotation *>(perLineData[ldMargin])->SetStyle(line, style);
  1784. NotifyModified(DocModification(SC_MOD_CHANGEMARGIN, LineStart(line), 0, 0, 0, line));
  1785. }
  1786. void Document::MarginSetStyles(int line, const unsigned char *styles) {
  1787. static_cast<LineAnnotation *>(perLineData[ldMargin])->SetStyles(line, styles);
  1788. NotifyModified(DocModification(SC_MOD_CHANGEMARGIN, LineStart(line), 0, 0, 0, line));
  1789. }
  1790. void Document::MarginClearAll() {
  1791. int maxEditorLine = LinesTotal();
  1792. for (int l=0; l<maxEditorLine; l++)
  1793. MarginSetText(l, 0);
  1794. // Free remaining data
  1795. static_cast<LineAnnotation *>(perLineData[ldMargin])->ClearAll();
  1796. }
  1797. StyledText Document::AnnotationStyledText(int line) const {
  1798. LineAnnotation *pla = static_cast<LineAnnotation *>(perLineData[ldAnnotation]);
  1799. return StyledText(pla->Length(line), pla->Text(line),
  1800. pla->MultipleStyles(line), pla->Style(line), pla->Styles(line));
  1801. }
  1802. void Document::AnnotationSetText(int line, const char *text) {
  1803. if (line >= 0 && line < LinesTotal()) {
  1804. const int linesBefore = AnnotationLines(line);
  1805. static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetText(line, text);
  1806. const int linesAfter = AnnotationLines(line);
  1807. DocModification mh(SC_MOD_CHANGEANNOTATION, LineStart(line), 0, 0, 0, line);
  1808. mh.annotationLinesAdded = linesAfter - linesBefore;
  1809. NotifyModified(mh);
  1810. }
  1811. }
  1812. void Document::AnnotationSetStyle(int line, int style) {
  1813. static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetStyle(line, style);
  1814. DocModification mh(SC_MOD_CHANGEANNOTATION, LineStart(line), 0, 0, 0, line);
  1815. NotifyModified(mh);
  1816. }
  1817. void Document::AnnotationSetStyles(int line, const unsigned char *styles) {
  1818. if (line >= 0 && line < LinesTotal()) {
  1819. static_cast<LineAnnotation *>(perLineData[ldAnnotation])->SetStyles(line, styles);
  1820. }
  1821. }
  1822. int Document::AnnotationLines(int line) const {
  1823. return static_cast<LineAnnotation *>(perLineData[ldAnnotation])->Lines(line);
  1824. }
  1825. void Document::AnnotationClearAll() {
  1826. int maxEditorLine = LinesTotal();
  1827. for (int l=0; l<maxEditorLine; l++)
  1828. AnnotationSetText(l, 0);
  1829. // Free remaining data
  1830. static_cast<LineAnnotation *>(perLineData[ldAnnotation])->ClearAll();
  1831. }
  1832. void Document::IncrementStyleClock() {
  1833. styleClock = (styleClock + 1) % 0x100000;
  1834. }
  1835. void SCI_METHOD Document::DecorationFillRange(int position, int value, int fillLength) {
  1836. if (decorations.FillRange(position, value, fillLength)) {
  1837. DocModification mh(SC_MOD_CHANGEINDICATOR | SC_PERFORMED_USER,
  1838. position, fillLength);
  1839. NotifyModified(mh);
  1840. }
  1841. }
  1842. bool Document::AddWatcher(DocWatcher *watcher, void *userData) {
  1843. WatcherWithUserData wwud(watcher, userData);
  1844. std::vector<WatcherWithUserData>::iterator it =
  1845. std::find(watchers.begin(), watchers.end(), wwud);
  1846. if (it != watchers.end())
  1847. return false;
  1848. watchers.push_back(wwud);
  1849. return true;
  1850. }
  1851. bool Document::RemoveWatcher(DocWatcher *watcher, void *userData) {
  1852. std::vector<WatcherWithUserData>::iterator it =
  1853. std::find(watchers.begin(), watchers.end(), WatcherWithUserData(watcher, userData));
  1854. if (it != watchers.end()) {
  1855. watchers.erase(it);
  1856. return true;
  1857. }
  1858. return false;
  1859. }
  1860. void Document::NotifyModifyAttempt() {
  1861. for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
  1862. it->watcher->NotifyModifyAttempt(this, it->userData);
  1863. }
  1864. }
  1865. void Document::NotifySavePoint(bool atSavePoint) {
  1866. for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
  1867. it->watcher->NotifySavePoint(this, it->userData, atSavePoint);
  1868. }
  1869. }
  1870. void Document::NotifyModified(DocModification mh) {
  1871. if (mh.modificationType & SC_MOD_INSERTTEXT) {
  1872. decorations.InsertSpace(mh.position, mh.length);
  1873. } else if (mh.modificationType & SC_MOD_DELETETEXT) {
  1874. decorations.DeleteRange(mh.position, mh.length);
  1875. }
  1876. for (std::vector<WatcherWithUserData>::iterator it = watchers.begin(); it != watchers.end(); ++it) {
  1877. it->watcher->NotifyModified(this, mh, it->userData);
  1878. }
  1879. }
  1880. bool Document::IsWordPartSeparator(char ch) const {
  1881. return (WordCharClass(ch) == CharClassify::ccWord) && IsPunctuation(ch);
  1882. }
  1883. int Document::WordPartLeft(int pos) {
  1884. if (pos > 0) {
  1885. --pos;
  1886. char startChar = cb.CharAt(pos);
  1887. if (IsWordPartSeparator(startChar)) {
  1888. while (pos > 0 && IsWordPartSeparator(cb.CharAt(pos))) {
  1889. --pos;
  1890. }
  1891. }
  1892. if (pos > 0) {
  1893. startChar = cb.CharAt(pos);
  1894. --pos;
  1895. if (IsLowerCase(startChar)) {
  1896. while (pos > 0 && IsLowerCase(cb.CharAt(pos)))
  1897. --pos;
  1898. if (!IsUpperCase(cb.CharAt(pos)) && !IsLowerCase(cb.CharAt(pos)))
  1899. ++pos;
  1900. } else if (IsUpperCase(startChar)) {
  1901. while (pos > 0 && IsUpperCase(cb.CharAt(pos)))
  1902. --pos;
  1903. if (!IsUpperCase(cb.CharAt(pos)))
  1904. ++pos;
  1905. } else if (IsADigit(startChar)) {
  1906. while (pos > 0 && IsADigit(cb.CharAt(pos)))
  1907. --pos;
  1908. if (!IsADigit(cb.CharAt(pos)))
  1909. ++pos;
  1910. } else if (IsPunctuation(startChar)) {
  1911. while (pos > 0 && IsPunctuation(cb.CharAt(pos)))
  1912. --pos;
  1913. if (!IsPunctuation(cb.CharAt(pos)))
  1914. ++pos;
  1915. } else if (isspacechar(startChar)) {
  1916. while (pos > 0 && isspacechar(cb.CharAt(pos)))
  1917. --pos;
  1918. if (!isspacechar(cb.CharAt(pos)))
  1919. ++pos;
  1920. } else if (!IsASCII(startChar)) {
  1921. while (pos > 0 && !IsASCII(cb.CharAt(pos)))
  1922. --pos;
  1923. if (IsASCII(cb.CharAt(pos)))
  1924. ++pos;
  1925. } else {
  1926. ++pos;
  1927. }
  1928. }
  1929. }
  1930. return pos;
  1931. }
  1932. int Document::WordPartRight(int pos) {
  1933. char startChar = cb.CharAt(pos);
  1934. int length = Length();
  1935. if (IsWordPartSeparator(startChar)) {
  1936. while (pos < length && IsWordPartSeparator(cb.CharAt(pos)))
  1937. ++pos;
  1938. startChar = cb.CharAt(pos);
  1939. }
  1940. if (!IsASCII(startChar)) {
  1941. while (pos < length && !IsASCII(cb.CharAt(pos)))
  1942. ++pos;
  1943. } else if (IsLowerCase(startChar)) {
  1944. while (pos < length && IsLowerCase(cb.CharAt(pos)))
  1945. ++pos;
  1946. } else if (IsUpperCase(startChar)) {
  1947. if (IsLowerCase(cb.CharAt(pos + 1))) {
  1948. ++pos;
  1949. while (pos < length && IsLowerCase(cb.CharAt(pos)))
  1950. ++pos;
  1951. } else {
  1952. while (pos < length && IsUpperCase(cb.CharAt(pos)))
  1953. ++pos;
  1954. }
  1955. if (IsLowerCase(cb.CharAt(pos)) && IsUpperCase(cb.CharAt(pos - 1)))
  1956. --pos;
  1957. } else if (IsADigit(startChar)) {
  1958. while (pos < length && IsADigit(cb.CharAt(pos)))
  1959. ++pos;
  1960. } else if (IsPunctuation(startChar)) {
  1961. while (pos < length && IsPunctuation(cb.CharAt(pos)))
  1962. ++pos;
  1963. } else if (isspacechar(startChar)) {
  1964. while (pos < length && isspacechar(cb.CharAt(pos)))
  1965. ++pos;
  1966. } else {
  1967. ++pos;
  1968. }
  1969. return pos;
  1970. }
  1971. bool IsLineEndChar(char c) {
  1972. return (c == '\n' || c == '\r');
  1973. }
  1974. int Document::ExtendStyleRange(int pos, int delta, bool singleLine) {
  1975. int sStart = cb.StyleAt(pos);
  1976. if (delta < 0) {
  1977. while (pos > 0 && (cb.StyleAt(pos) == sStart) && (!singleLine || !IsLineEndChar(cb.CharAt(pos))))
  1978. pos--;
  1979. pos++;
  1980. } else {
  1981. while (pos < (Length()) && (cb.StyleAt(pos) == sStart) && (!singleLine || !IsLineEndChar(cb.CharAt(pos))))
  1982. pos++;
  1983. }
  1984. return pos;
  1985. }
  1986. static char BraceOpposite(char ch) {
  1987. switch (ch) {
  1988. case '(':
  1989. return ')';
  1990. case ')':
  1991. return '(';
  1992. case '[':
  1993. return ']';
  1994. case ']':
  1995. return '[';
  1996. case '{':
  1997. return '}';
  1998. case '}':
  1999. return '{';
  2000. case '<':
  2001. return '>';
  2002. case '>':
  2003. return '<';
  2004. default:
  2005. return '\0';
  2006. }
  2007. }
  2008. // TODO: should be able to extend styled region to find matching brace
  2009. int Document::BraceMatch(int position, int /*maxReStyle*/) {
  2010. char chBrace = CharAt(position);
  2011. char chSeek = BraceOpposite(chBrace);
  2012. if (chSeek == '\0')
  2013. return - 1;
  2014. char styBrace = static_cast<char>(StyleAt(position));
  2015. int direction = -1;
  2016. if (chBrace == '(' || chBrace == '[' || chBrace == '{' || chBrace == '<')
  2017. direction = 1;
  2018. int depth = 1;
  2019. position = NextPosition(position, direction);
  2020. while ((position >= 0) && (position < Length())) {
  2021. char chAtPos = CharAt(position);
  2022. char styAtPos = static_cast<char>(StyleAt(position));
  2023. if ((position > GetEndStyled()) || (styAtPos == styBrace)) {
  2024. if (chAtPos == chBrace)
  2025. depth++;
  2026. if (chAtPos == chSeek)
  2027. depth--;
  2028. if (depth == 0)
  2029. return position;
  2030. }
  2031. int positionBeforeMove = position;
  2032. position = NextPosition(position, direction);
  2033. if (position == positionBeforeMove)
  2034. break;
  2035. }
  2036. return - 1;
  2037. }
  2038. /**
  2039. * Implementation of RegexSearchBase for the default built-in regular expression engine
  2040. */
  2041. class BuiltinRegex : public RegexSearchBase {
  2042. public:
  2043. explicit BuiltinRegex(CharClassify *charClassTable) : search(charClassTable) {}
  2044. virtual ~BuiltinRegex() {
  2045. }
  2046. virtual long FindText(Document *doc, int minPos, int maxPos, const char *s,
  2047. bool caseSensitive, bool word, bool wordStart, int flags,
  2048. int *length);
  2049. virtual const char *SubstituteByPosition(Document *doc, const char *text, int *length);
  2050. private:
  2051. RESearch search;
  2052. std::string substituted;
  2053. };
  2054. namespace {
  2055. /**
  2056. * RESearchRange keeps track of search range.
  2057. */
  2058. class RESearchRange {
  2059. public:
  2060. const Document *doc;
  2061. int increment;
  2062. int startPos;
  2063. int endPos;
  2064. int lineRangeStart;
  2065. int lineRangeEnd;
  2066. int lineRangeBreak;
  2067. RESearchRange(const Document *doc_, int minPos, int maxPos) : doc(doc_) {
  2068. increment = (minPos <= maxPos) ? 1 : -1;
  2069. // Range endpoints should not be inside DBCS characters, but just in case, move them.
  2070. startPos = doc->MovePositionOutsideChar(minPos, 1, false);
  2071. endPos = doc->MovePositionOutsideChar(maxPos, 1, false);
  2072. lineRangeStart = doc->LineFromPosition(startPos);
  2073. lineRangeEnd = doc->LineFromPosition(endPos);
  2074. if ((increment == 1) &&
  2075. (startPos >= doc->LineEnd(lineRangeStart)) &&
  2076. (lineRangeStart < lineRangeEnd)) {
  2077. // the start position is at end of line or between line end characters.
  2078. lineRangeStart++;
  2079. startPos = doc->LineStart(lineRangeStart);
  2080. } else if ((increment == -1) &&
  2081. (startPos <= doc->LineStart(lineRangeStart)) &&
  2082. (lineRangeStart > lineRangeEnd)) {
  2083. // the start position is at beginning of line.
  2084. lineRangeStart--;
  2085. startPos = doc->LineEnd(lineRangeStart);
  2086. }
  2087. lineRangeBreak = lineRangeEnd + increment;
  2088. }
  2089. Range LineRange(int line) const {
  2090. Range range(doc->LineStart(line), doc->LineEnd(line));
  2091. if (increment == 1) {
  2092. if (line == lineRangeStart)
  2093. range.start = startPos;
  2094. if (line == lineRangeEnd)
  2095. range.end = endPos;
  2096. } else {
  2097. if (line == lineRangeEnd)
  2098. range.start = endPos;
  2099. if (line == lineRangeStart)
  2100. range.end = startPos;
  2101. }
  2102. return range;
  2103. }
  2104. };
  2105. // Define a way for the Regular Expression code to access the document
  2106. class DocumentIndexer : public CharacterIndexer {
  2107. Document *pdoc;
  2108. int end;
  2109. public:
  2110. DocumentIndexer(Document *pdoc_, int end_) :
  2111. pdoc(pdoc_), end(end_) {
  2112. }
  2113. virtual ~DocumentIndexer() {
  2114. }
  2115. virtual char CharAt(int index) {
  2116. if (index < 0 || index >= end)
  2117. return 0;
  2118. else
  2119. return pdoc->CharAt(index);
  2120. }
  2121. };
  2122. #ifdef CXX11_REGEX
  2123. class ByteIterator : public std::iterator<std::bidirectional_iterator_tag, char> {
  2124. public:
  2125. const Document *doc;
  2126. Position position;
  2127. ByteIterator(const Document *doc_ = 0, Position position_ = 0) : doc(doc_), position(position_) {
  2128. }
  2129. ByteIterator(const ByteIterator &other) {
  2130. doc = other.doc;
  2131. position = other.position;
  2132. }
  2133. ByteIterator &operator=(const ByteIterator &other) {
  2134. if (this != &other) {
  2135. doc = other.doc;
  2136. position = other.position;
  2137. }
  2138. return *this;
  2139. }
  2140. char operator*() const {
  2141. return doc->CharAt(position);
  2142. }
  2143. ByteIterator &operator++() {
  2144. position++;
  2145. return *this;
  2146. }
  2147. ByteIterator operator++(int) {
  2148. ByteIterator retVal(*this);
  2149. position++;
  2150. return retVal;
  2151. }
  2152. ByteIterator &operator--() {
  2153. position--;
  2154. return *this;
  2155. }
  2156. bool operator==(const ByteIterator &other) const {
  2157. return doc == other.doc && position == other.position;
  2158. }
  2159. bool operator!=(const ByteIterator &other) const {
  2160. return doc != other.doc || position != other.position;
  2161. }
  2162. int Pos() const {
  2163. return position;
  2164. }
  2165. int PosRoundUp() const {
  2166. return position;
  2167. }
  2168. };
  2169. // On Windows, wchar_t is 16 bits wide and on Unix it is 32 bits wide.
  2170. // Would be better to use sizeof(wchar_t) or similar to differentiate
  2171. // but easier for now to hard-code platforms.
  2172. // C++11 has char16_t and char32_t but neither Clang nor Visual C++
  2173. // appear to allow specializing basic_regex over these.
  2174. #ifdef _WIN32
  2175. #define WCHAR_T_IS_16 1
  2176. #else
  2177. #define WCHAR_T_IS_16 0
  2178. #endif
  2179. #if WCHAR_T_IS_16
  2180. // On Windows, report non-BMP characters as 2 separate surrogates as that
  2181. // matches wregex since it is based on wchar_t.
  2182. class UTF8Iterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t> {
  2183. // These 3 fields determine the iterator position and are used for comparisons
  2184. const Document *doc;
  2185. Position position;
  2186. size_t characterIndex;
  2187. // Remaining fields are derived from the determining fields so are excluded in comparisons
  2188. unsigned int lenBytes;
  2189. size_t lenCharacters;
  2190. wchar_t buffered[2];
  2191. public:
  2192. UTF8Iterator(const Document *doc_ = 0, Position position_ = 0) :
  2193. doc(doc_), position(position_), characterIndex(0), lenBytes(0), lenCharacters(0) {
  2194. buffered[0] = 0;
  2195. buffered[1] = 0;
  2196. if (doc) {
  2197. ReadCharacter();
  2198. }
  2199. }
  2200. UTF8Iterator(const UTF8Iterator &other) {
  2201. doc = other.doc;
  2202. position = other.position;
  2203. characterIndex = other.characterIndex;
  2204. lenBytes = other.lenBytes;
  2205. lenCharacters = other.lenCharacters;
  2206. buffered[0] = other.buffered[0];
  2207. buffered[1] = other.buffered[1];
  2208. }
  2209. UTF8Iterator &operator=(const UTF8Iterator &other) {
  2210. if (this != &other) {
  2211. doc = other.doc;
  2212. position = other.position;
  2213. characterIndex = other.characterIndex;
  2214. lenBytes = other.lenBytes;
  2215. lenCharacters = other.lenCharacters;
  2216. buffered[0] = other.buffered[0];
  2217. buffered[1] = other.buffered[1];
  2218. }
  2219. return *this;
  2220. }
  2221. wchar_t operator*() const {
  2222. assert(lenCharacters != 0);
  2223. return buffered[characterIndex];
  2224. }
  2225. UTF8Iterator &operator++() {
  2226. if ((characterIndex + 1) < (lenCharacters)) {
  2227. characterIndex++;
  2228. } else {
  2229. position += lenBytes;
  2230. ReadCharacter();
  2231. characterIndex = 0;
  2232. }
  2233. return *this;
  2234. }
  2235. UTF8Iterator operator++(int) {
  2236. UTF8Iterator retVal(*this);
  2237. if ((characterIndex + 1) < (lenCharacters)) {
  2238. characterIndex++;
  2239. } else {
  2240. position += lenBytes;
  2241. ReadCharacter();
  2242. characterIndex = 0;
  2243. }
  2244. return retVal;
  2245. }
  2246. UTF8Iterator &operator--() {
  2247. if (characterIndex) {
  2248. characterIndex--;
  2249. } else {
  2250. position = doc->NextPosition(position, -1);
  2251. ReadCharacter();
  2252. characterIndex = lenCharacters - 1;
  2253. }
  2254. return *this;
  2255. }
  2256. bool operator==(const UTF8Iterator &other) const {
  2257. // Only test the determining fields, not the character widths and values derived from this
  2258. return doc == other.doc &&
  2259. position == other.position &&
  2260. characterIndex == other.characterIndex;
  2261. }
  2262. bool operator!=(const UTF8Iterator &other) const {
  2263. // Only test the determining fields, not the character widths and values derived from this
  2264. return doc != other.doc ||
  2265. position != other.position ||
  2266. characterIndex != other.characterIndex;
  2267. }
  2268. int Pos() const {
  2269. return position;
  2270. }
  2271. int PosRoundUp() const {
  2272. if (characterIndex)
  2273. return position + lenBytes; // Force to end of character
  2274. else
  2275. return position;
  2276. }
  2277. private:
  2278. void ReadCharacter() {
  2279. Document::CharacterExtracted charExtracted = doc->ExtractCharacter(position);
  2280. lenBytes = charExtracted.widthBytes;
  2281. if (charExtracted.character == unicodeReplacementChar) {
  2282. lenCharacters = 1;
  2283. buffered[0] = static_cast<wchar_t>(charExtracted.character);
  2284. } else {
  2285. lenCharacters = UTF16FromUTF32Character(charExtracted.character, buffered);
  2286. }
  2287. }
  2288. };
  2289. #else
  2290. // On Unix, report non-BMP characters as single characters
  2291. class UTF8Iterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t> {
  2292. const Document *doc;
  2293. Position position;
  2294. public:
  2295. UTF8Iterator(const Document *doc_=0, Position position_=0) : doc(doc_), position(position_) {
  2296. }
  2297. UTF8Iterator(const UTF8Iterator &other) {
  2298. doc = other.doc;
  2299. position = other.position;
  2300. }
  2301. UTF8Iterator &operator=(const UTF8Iterator &other) {
  2302. if (this != &other) {
  2303. doc = other.doc;
  2304. position = other.position;
  2305. }
  2306. return *this;
  2307. }
  2308. wchar_t operator*() const {
  2309. Document::CharacterExtracted charExtracted = doc->ExtractCharacter(position);
  2310. return charExtracted.character;
  2311. }
  2312. UTF8Iterator &operator++() {
  2313. position = doc->NextPosition(position, 1);
  2314. return *this;
  2315. }
  2316. UTF8Iterator operator++(int) {
  2317. UTF8Iterator retVal(*this);
  2318. position = doc->NextPosition(position, 1);
  2319. return retVal;
  2320. }
  2321. UTF8Iterator &operator--() {
  2322. position = doc->NextPosition(position, -1);
  2323. return *this;
  2324. }
  2325. bool operator==(const UTF8Iterator &other) const {
  2326. return doc == other.doc && position == other.position;
  2327. }
  2328. bool operator!=(const UTF8Iterator &other) const {
  2329. return doc != other.doc || position != other.position;
  2330. }
  2331. int Pos() const {
  2332. return position;
  2333. }
  2334. int PosRoundUp() const {
  2335. return position;
  2336. }
  2337. };
  2338. #endif
  2339. std::regex_constants::match_flag_type MatchFlags(const Document *doc, int startPos, int endPos) {
  2340. std::regex_constants::match_flag_type flagsMatch = std::regex_constants::match_default;
  2341. if (!doc->IsLineStartPosition(startPos))
  2342. flagsMatch |= std::regex_constants::match_not_bol;
  2343. if (!doc->IsLineEndPosition(endPos))
  2344. flagsMatch |= std::regex_constants::match_not_eol;
  2345. return flagsMatch;
  2346. }
  2347. template<typename Iterator, typename Regex>
  2348. bool MatchOnLines(const Document *doc, const Regex &regexp, const RESearchRange &resr, RESearch &search) {
  2349. bool matched = false;
  2350. std::match_results<Iterator> match;
  2351. // MSVC and libc++ have problems with ^ and $ matching line ends inside a range
  2352. // If they didn't then the line by line iteration could be removed for the forwards
  2353. // case and replaced with the following 4 lines:
  2354. // Iterator uiStart(doc, startPos);
  2355. // Iterator uiEnd(doc, endPos);
  2356. // flagsMatch = MatchFlags(doc, startPos, endPos);
  2357. // matched = std::regex_search(uiStart, uiEnd, match, regexp, flagsMatch);
  2358. // Line by line.
  2359. for (int line = resr.lineRangeStart; line != resr.lineRangeBreak; line += resr.increment) {
  2360. const Range lineRange = resr.LineRange(line);
  2361. Iterator itStart(doc, lineRange.start);
  2362. Iterator itEnd(doc, lineRange.end);
  2363. std::regex_constants::match_flag_type flagsMatch = MatchFlags(doc, lineRange.start, lineRange.end);
  2364. matched = std::regex_search(itStart, itEnd, match, regexp, flagsMatch);
  2365. // Check for the last match on this line.
  2366. if (matched) {
  2367. if (resr.increment == -1) {
  2368. while (matched) {
  2369. Iterator itNext(doc, match[0].second.PosRoundUp());
  2370. flagsMatch = MatchFlags(doc, itNext.Pos(), lineRange.end);
  2371. std::match_results<Iterator> matchNext;
  2372. matched = std::regex_search(itNext, itEnd, matchNext, regexp, flagsMatch);
  2373. if (matched) {
  2374. if (match[0].first == match[0].second) {
  2375. // Empty match means failure so exit
  2376. return false;
  2377. }
  2378. match = matchNext;
  2379. }
  2380. }
  2381. matched = true;
  2382. }
  2383. break;
  2384. }
  2385. }
  2386. if (matched) {
  2387. for (size_t co = 0; co < match.size(); co++) {
  2388. search.bopat[co] = match[co].first.Pos();
  2389. search.eopat[co] = match[co].second.PosRoundUp();
  2390. size_t lenMatch = search.eopat[co] - search.bopat[co];
  2391. search.pat[co].resize(lenMatch);
  2392. for (size_t iPos = 0; iPos < lenMatch; iPos++) {
  2393. search.pat[co][iPos] = doc->CharAt(iPos + search.bopat[co]);
  2394. }
  2395. }
  2396. }
  2397. return matched;
  2398. }
  2399. long Cxx11RegexFindText(Document *doc, int minPos, int maxPos, const char *s,
  2400. bool caseSensitive, int *length, RESearch &search) {
  2401. const RESearchRange resr(doc, minPos, maxPos);
  2402. try {
  2403. //ElapsedTime et;
  2404. std::regex::flag_type flagsRe = std::regex::ECMAScript;
  2405. // Flags that apper to have no effect:
  2406. // | std::regex::collate | std::regex::extended;
  2407. if (!caseSensitive)
  2408. flagsRe = flagsRe | std::regex::icase;
  2409. // Clear the RESearch so can fill in matches
  2410. search.Clear();
  2411. bool matched = false;
  2412. if (SC_CP_UTF8 == doc->dbcsCodePage) {
  2413. unsigned int lenS = static_cast<unsigned int>(strlen(s));
  2414. std::vector<wchar_t> ws(lenS + 1);
  2415. #if WCHAR_T_IS_16
  2416. size_t outLen = UTF16FromUTF8(s, lenS, &ws[0], lenS);
  2417. #else
  2418. size_t outLen = UTF32FromUTF8(s, lenS, reinterpret_cast<unsigned int *>(&ws[0]), lenS);
  2419. #endif
  2420. ws[outLen] = 0;
  2421. std::wregex regexp;
  2422. #if defined(__APPLE__)
  2423. // Using a UTF-8 locale doesn't change to Unicode over a byte buffer so '.'
  2424. // is one byte not one character.
  2425. // However, on OS X this makes wregex act as Unicode
  2426. std::locale localeU("en_US.UTF-8");
  2427. regexp.imbue(localeU);
  2428. #endif
  2429. regexp.assign(&ws[0], flagsRe);
  2430. matched = MatchOnLines<UTF8Iterator>(doc, regexp, resr, search);
  2431. } else {
  2432. std::regex regexp;
  2433. regexp.assign(s, flagsRe);
  2434. matched = MatchOnLines<ByteIterator>(doc, regexp, resr, search);
  2435. }
  2436. int posMatch = -1;
  2437. if (matched) {
  2438. posMatch = search.bopat[0];
  2439. *length = search.eopat[0] - search.bopat[0];
  2440. }
  2441. // Example - search in doc/ScintillaHistory.html for
  2442. // [[:upper:]]eta[[:space:]]
  2443. // On MacBook, normally around 1 second but with locale imbued -> 14 seconds.
  2444. //double durSearch = et.Duration(true);
  2445. //Platform::DebugPrintf("Search:%9.6g \n", durSearch);
  2446. return posMatch;
  2447. } catch (std::regex_error &) {
  2448. // Failed to create regular expression
  2449. throw RegexError();
  2450. } catch (...) {
  2451. // Failed in some other way
  2452. return -1;
  2453. }
  2454. }
  2455. #endif
  2456. }
  2457. long BuiltinRegex::FindText(Document *doc, int minPos, int maxPos, const char *s,
  2458. bool caseSensitive, bool, bool, int flags,
  2459. int *length) {
  2460. #ifdef CXX11_REGEX
  2461. if (flags & SCFIND_CXX11REGEX) {
  2462. return Cxx11RegexFindText(doc, minPos, maxPos, s,
  2463. caseSensitive, length, search);
  2464. }
  2465. #endif
  2466. const RESearchRange resr(doc, minPos, maxPos);
  2467. const bool posix = (flags & SCFIND_POSIX) != 0;
  2468. const char *errmsg = search.Compile(s, *length, caseSensitive, posix);
  2469. if (errmsg) {
  2470. return -1;
  2471. }
  2472. // Find a variable in a property file: \$(\([A-Za-z0-9_.]+\))
  2473. // Replace first '.' with '-' in each property file variable reference:
  2474. // Search: \$(\([A-Za-z0-9_-]+\)\.\([A-Za-z0-9_.]+\))
  2475. // Replace: $(\1-\2)
  2476. int pos = -1;
  2477. int lenRet = 0;
  2478. const char searchEnd = s[*length - 1];
  2479. const char searchEndPrev = (*length > 1) ? s[*length - 2] : '\0';
  2480. for (int line = resr.lineRangeStart; line != resr.lineRangeBreak; line += resr.increment) {
  2481. int startOfLine = doc->LineStart(line);
  2482. int endOfLine = doc->LineEnd(line);
  2483. if (resr.increment == 1) {
  2484. if (line == resr.lineRangeStart) {
  2485. if ((resr.startPos != startOfLine) && (s[0] == '^'))
  2486. continue; // Can't match start of line if start position after start of line
  2487. startOfLine = resr.startPos;
  2488. }
  2489. if (line == resr.lineRangeEnd) {
  2490. if ((resr.endPos != endOfLine) && (searchEnd == '$') && (searchEndPrev != '\\'))
  2491. continue; // Can't match end of line if end position before end of line
  2492. endOfLine = resr.endPos;
  2493. }
  2494. } else {
  2495. if (line == resr.lineRangeEnd) {
  2496. if ((resr.endPos != startOfLine) && (s[0] == '^'))
  2497. continue; // Can't match start of line if end position after start of line
  2498. startOfLine = resr.endPos;
  2499. }
  2500. if (line == resr.lineRangeStart) {
  2501. if ((resr.startPos != endOfLine) && (searchEnd == '$') && (searchEndPrev != '\\'))
  2502. continue; // Can't match end of line if start position before end of line
  2503. endOfLine = resr.startPos;
  2504. }
  2505. }
  2506. DocumentIndexer di(doc, endOfLine);
  2507. int success = search.Execute(di, startOfLine, endOfLine);
  2508. if (success) {
  2509. pos = search.bopat[0];
  2510. // Ensure only whole characters selected
  2511. search.eopat[0] = doc->MovePositionOutsideChar(search.eopat[0], 1, false);
  2512. lenRet = search.eopat[0] - search.bopat[0];
  2513. // There can be only one start of a line, so no need to look for last match in line
  2514. if ((resr.increment == -1) && (s[0] != '^')) {
  2515. // Check for the last match on this line.
  2516. int repetitions = 1000; // Break out of infinite loop
  2517. while (success && (search.eopat[0] <= endOfLine) && (repetitions--)) {
  2518. success = search.Execute(di, pos+1, endOfLine);
  2519. if (success) {
  2520. if (search.eopat[0] <= minPos) {
  2521. pos = search.bopat[0];
  2522. lenRet = search.eopat[0] - search.bopat[0];
  2523. } else {
  2524. success = 0;
  2525. }
  2526. }
  2527. }
  2528. }
  2529. break;
  2530. }
  2531. }
  2532. *length = lenRet;
  2533. return pos;
  2534. }
  2535. const char *BuiltinRegex::SubstituteByPosition(Document *doc, const char *text, int *length) {
  2536. substituted.clear();
  2537. DocumentIndexer di(doc, doc->Length());
  2538. search.GrabMatches(di);
  2539. for (int j = 0; j < *length; j++) {
  2540. if (text[j] == '\\') {
  2541. if (text[j + 1] >= '0' && text[j + 1] <= '9') {
  2542. unsigned int patNum = text[j + 1] - '0';
  2543. unsigned int len = search.eopat[patNum] - search.bopat[patNum];
  2544. if (!search.pat[patNum].empty()) // Will be null if try for a match that did not occur
  2545. substituted.append(search.pat[patNum].c_str(), len);
  2546. j++;
  2547. } else {
  2548. j++;
  2549. switch (text[j]) {
  2550. case 'a':
  2551. substituted.push_back('\a');
  2552. break;
  2553. case 'b':
  2554. substituted.push_back('\b');
  2555. break;
  2556. case 'f':
  2557. substituted.push_back('\f');
  2558. break;
  2559. case 'n':
  2560. substituted.push_back('\n');
  2561. break;
  2562. case 'r':
  2563. substituted.push_back('\r');
  2564. break;
  2565. case 't':
  2566. substituted.push_back('\t');
  2567. break;
  2568. case 'v':
  2569. substituted.push_back('\v');
  2570. break;
  2571. case '\\':
  2572. substituted.push_back('\\');
  2573. break;
  2574. default:
  2575. substituted.push_back('\\');
  2576. j--;
  2577. }
  2578. }
  2579. } else {
  2580. substituted.push_back(text[j]);
  2581. }
  2582. }
  2583. *length = static_cast<int>(substituted.length());
  2584. return substituted.c_str();
  2585. }
  2586. #ifndef SCI_OWNREGEX
  2587. #ifdef SCI_NAMESPACE
  2588. RegexSearchBase *Scintilla::CreateRegexSearch(CharClassify *charClassTable) {
  2589. return new BuiltinRegex(charClassTable);
  2590. }
  2591. #else
  2592. RegexSearchBase *CreateRegexSearch(CharClassify *charClassTable) {
  2593. return new BuiltinRegex(charClassTable);
  2594. }
  2595. #endif
  2596. #endif