PageRenderTime 66ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file