pieceTreeBase.ts 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031
  1. /** reference from https://github.com/microsoft/vscode */
  2. import { CharCode } from '../common/charCode';
  3. import { Position } from '../common/position';
  4. import { Range } from '../common/range';
  5. import { FindMatch, ITextSnapshot, SearchData } from '../common/model';
  6. import {
  7. NodeColor,
  8. SENTINEL,
  9. TreeNode,
  10. fixInsert,
  11. leftest,
  12. rbDelete,
  13. righttest,
  14. updateTreeMetadata,
  15. } from './rbTreeBase';
  16. import { Searcher, createFindMatch, isValidMatch } from '../model/textModelSearch';
  17. // const lfRegex = new RegExp(/\r\n|\r|\n/g);
  18. const AverageBufferSize = 65535;
  19. function createUintArray(arr: number[]): Uint32Array | Uint16Array {
  20. let r;
  21. if (arr[arr.length - 1] < 65536) {
  22. r = new Uint16Array(arr.length);
  23. } else {
  24. r = new Uint32Array(arr.length);
  25. }
  26. r.set(arr, 0);
  27. return r;
  28. }
  29. class LineStarts {
  30. constructor(
  31. public readonly lineStarts: Uint32Array | Uint16Array | number[],
  32. public readonly cr: number,
  33. public readonly lf: number,
  34. public readonly crlf: number,
  35. public readonly isBasicASCII: boolean
  36. ) {}
  37. }
  38. export function createLineStartsFast(str: string, readonly: boolean = true): Uint32Array | Uint16Array | number[] {
  39. const r: number[] = [0];
  40. let rLength = 1;
  41. for (let i = 0, len = str.length; i < len; i++) {
  42. const chr = str.charCodeAt(i);
  43. if (chr === CharCode.CarriageReturn) {
  44. if (i + 1 < len && str.charCodeAt(i + 1) === CharCode.LineFeed) {
  45. // \r\n... case
  46. r[rLength++] = i + 2;
  47. i++; // skip \n
  48. } else {
  49. // \r... case
  50. r[rLength++] = i + 1;
  51. }
  52. } else if (chr === CharCode.LineFeed) {
  53. r[rLength++] = i + 1;
  54. }
  55. }
  56. if (readonly) {
  57. return createUintArray(r);
  58. } else {
  59. return r;
  60. }
  61. }
  62. export function createLineStarts(r: number[], str: string): LineStarts {
  63. r.length = 0;
  64. r[0] = 0;
  65. let rLength = 1;
  66. let cr = 0,
  67. lf = 0,
  68. crlf = 0;
  69. let isBasicASCII = true;
  70. for (let i = 0, len = str.length; i < len; i++) {
  71. const chr = str.charCodeAt(i);
  72. if (chr === CharCode.CarriageReturn) {
  73. if (i + 1 < len && str.charCodeAt(i + 1) === CharCode.LineFeed) {
  74. // \r\n... case
  75. crlf++;
  76. r[rLength++] = i + 2;
  77. i++; // skip \n
  78. } else {
  79. cr++;
  80. // \r... case
  81. r[rLength++] = i + 1;
  82. }
  83. } else if (chr === CharCode.LineFeed) {
  84. lf++;
  85. r[rLength++] = i + 1;
  86. } else {
  87. if (isBasicASCII) {
  88. if (chr !== CharCode.Tab && (chr < 32 || chr > 126)) {
  89. isBasicASCII = false;
  90. }
  91. }
  92. }
  93. }
  94. const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);
  95. r.length = 0;
  96. return result;
  97. }
  98. interface NodePosition {
  99. /**
  100. * Piece Index
  101. */
  102. node: TreeNode;
  103. /**
  104. * remainder in current piece.
  105. */
  106. remainder: number;
  107. /**
  108. * node start offset in document.
  109. */
  110. nodeStartOffset: number
  111. }
  112. export interface BufferCursor {
  113. /**
  114. * Line number in current buffer
  115. */
  116. line: number;
  117. /**
  118. * Column number in current buffer
  119. */
  120. column: number
  121. }
  122. export class Piece {
  123. readonly bufferIndex: number;
  124. readonly start: BufferCursor;
  125. readonly end: BufferCursor;
  126. readonly length: number;
  127. readonly lineFeedCnt: number;
  128. constructor(bufferIndex: number, start: BufferCursor, end: BufferCursor, lineFeedCnt: number, length: number) {
  129. this.bufferIndex = bufferIndex;
  130. this.start = start;
  131. this.end = end;
  132. this.lineFeedCnt = lineFeedCnt;
  133. this.length = length;
  134. }
  135. }
  136. export class StringBuffer {
  137. buffer: string;
  138. lineStarts: Uint32Array | Uint16Array | number[];
  139. constructor(buffer: string, lineStarts: Uint32Array | Uint16Array | number[]) {
  140. this.buffer = buffer;
  141. this.lineStarts = lineStarts;
  142. }
  143. }
  144. /**
  145. * Readonly snapshot for piece tree.
  146. * In a real multiple thread environment, to make snapshot reading always work correctly, we need to
  147. * 1. Make TreeNode.piece immutable, then reading and writing can run in parallel.
  148. * 2. TreeNode/Buffers normalization should not happen during snapshot reading.
  149. */
  150. class PieceTreeSnapshot implements ITextSnapshot {
  151. private readonly _pieces: Piece[];
  152. private _index: number;
  153. private readonly _tree: PieceTreeBase;
  154. private readonly _BOM: string;
  155. constructor(tree: PieceTreeBase, BOM: string) {
  156. this._pieces = [];
  157. this._tree = tree;
  158. this._BOM = BOM;
  159. this._index = 0;
  160. if (tree.root !== SENTINEL) {
  161. tree.iterate(tree.root, node => {
  162. if (node !== SENTINEL) {
  163. this._pieces.push(node.piece);
  164. }
  165. return true;
  166. });
  167. }
  168. }
  169. read(): string | null {
  170. if (this._pieces.length === 0) {
  171. if (this._index === 0) {
  172. this._index++;
  173. return this._BOM;
  174. } else {
  175. return null;
  176. }
  177. }
  178. if (this._index > this._pieces.length - 1) {
  179. return null;
  180. }
  181. if (this._index === 0) {
  182. return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]);
  183. }
  184. return this._tree.getPieceContent(this._pieces[this._index++]);
  185. }
  186. }
  187. interface CacheEntry {
  188. node: TreeNode;
  189. nodeStartOffset: number;
  190. nodeStartLineNumber?: number
  191. }
  192. class PieceTreeSearchCache {
  193. private readonly _limit: number;
  194. private _cache: CacheEntry[];
  195. constructor(limit: number) {
  196. this._limit = limit;
  197. this._cache = [];
  198. }
  199. public get(offset: number): CacheEntry | null {
  200. for (let i = this._cache.length - 1; i >= 0; i--) {
  201. const nodePos = this._cache[i];
  202. if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
  203. return nodePos;
  204. }
  205. }
  206. return null;
  207. }
  208. public get2(
  209. lineNumber: number
  210. ): {
  211. node: TreeNode;
  212. nodeStartOffset: number;
  213. nodeStartLineNumber: number
  214. } | null {
  215. for (let i = this._cache.length - 1; i >= 0; i--) {
  216. const nodePos = this._cache[i];
  217. if (
  218. nodePos.nodeStartLineNumber &&
  219. nodePos.nodeStartLineNumber < lineNumber &&
  220. nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber
  221. ) {
  222. return <
  223. {
  224. node: TreeNode;
  225. nodeStartOffset: number;
  226. nodeStartLineNumber: number
  227. }
  228. >nodePos;
  229. }
  230. }
  231. return null;
  232. }
  233. public set(nodePosition: CacheEntry) {
  234. if (this._cache.length >= this._limit) {
  235. this._cache.shift();
  236. }
  237. this._cache.push(nodePosition);
  238. }
  239. public validate(offset: number) {
  240. let hasInvalidVal = false;
  241. const tmp: Array<CacheEntry | null> = this._cache;
  242. for (let i = 0; i < tmp.length; i++) {
  243. const nodePos = tmp[i]!;
  244. if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
  245. tmp[i] = null;
  246. hasInvalidVal = true;
  247. continue;
  248. }
  249. }
  250. if (hasInvalidVal) {
  251. const newArr: CacheEntry[] = [];
  252. for (const entry of tmp) {
  253. if (entry !== null) {
  254. newArr.push(entry);
  255. }
  256. }
  257. this._cache = newArr;
  258. }
  259. }
  260. }
  261. export class PieceTreeBase {
  262. root!: TreeNode;
  263. protected _buffers!: StringBuffer[]; // 0 is change buffer, others are readonly original buffer.
  264. protected _lineCnt!: number;
  265. protected _length!: number;
  266. protected _EOL!: '\r\n' | '\n';
  267. protected _EOLLength!: number;
  268. protected _EOLNormalized!: boolean;
  269. private _lastChangeBufferPos!: BufferCursor;
  270. private _searchCache!: PieceTreeSearchCache;
  271. private _lastVisitedLine!: { lineNumber: number; value: string };
  272. constructor(chunks: StringBuffer[], eol: '\r\n' | '\n', eolNormalized: boolean) {
  273. this.create(chunks, eol, eolNormalized);
  274. }
  275. create(chunks: StringBuffer[], eol: '\r\n' | '\n', eolNormalized: boolean) {
  276. this._buffers = [new StringBuffer('', [0])];
  277. this._lastChangeBufferPos = { line: 0, column: 0 };
  278. this.root = SENTINEL;
  279. this._lineCnt = 1;
  280. this._length = 0;
  281. this._EOL = eol;
  282. this._EOLLength = eol.length;
  283. this._EOLNormalized = eolNormalized;
  284. let lastNode: TreeNode | null = null;
  285. for (let i = 0, len = chunks.length; i < len; i++) {
  286. if (chunks[i].buffer.length > 0) {
  287. if (!chunks[i].lineStarts) {
  288. chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer);
  289. }
  290. const piece = new Piece(
  291. i + 1,
  292. { line: 0, column: 0 },
  293. {
  294. line: chunks[i].lineStarts.length - 1,
  295. column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1],
  296. },
  297. chunks[i].lineStarts.length - 1,
  298. chunks[i].buffer.length
  299. );
  300. this._buffers.push(chunks[i]);
  301. lastNode = this.rbInsertRight(lastNode, piece);
  302. }
  303. }
  304. this._searchCache = new PieceTreeSearchCache(1);
  305. this._lastVisitedLine = { lineNumber: 0, value: '' };
  306. this.computeBufferMetadata();
  307. }
  308. normalizeEOL(eol: '\r\n' | '\n') {
  309. const averageBufferSize = AverageBufferSize;
  310. const min = averageBufferSize - Math.floor(averageBufferSize / 3);
  311. const max = min * 2;
  312. let tempChunk = '';
  313. let tempChunkLen = 0;
  314. const chunks: StringBuffer[] = [];
  315. this.iterate(this.root, node => {
  316. const str = this.getNodeContent(node);
  317. const len = str.length;
  318. if (tempChunkLen <= min || tempChunkLen + len < max) {
  319. tempChunk += str;
  320. tempChunkLen += len;
  321. return true;
  322. }
  323. // flush anyways
  324. const text = tempChunk.replace(/\r\n|\r|\n/g, eol);
  325. chunks.push(new StringBuffer(text, createLineStartsFast(text)));
  326. tempChunk = str;
  327. tempChunkLen = len;
  328. return true;
  329. });
  330. if (tempChunkLen > 0) {
  331. const text = tempChunk.replace(/\r\n|\r|\n/g, eol);
  332. chunks.push(new StringBuffer(text, createLineStartsFast(text)));
  333. }
  334. this.create(chunks, eol, true);
  335. }
  336. // #region Buffer API
  337. public getEOL(): '\r\n' | '\n' {
  338. return this._EOL;
  339. }
  340. public setEOL(newEOL: '\r\n' | '\n'): void {
  341. this._EOL = newEOL;
  342. this._EOLLength = this._EOL.length;
  343. this.normalizeEOL(newEOL);
  344. }
  345. public createSnapshot(BOM: string): ITextSnapshot {
  346. return new PieceTreeSnapshot(this, BOM);
  347. }
  348. public equal(other: PieceTreeBase): boolean {
  349. if (this.getLength() !== other.getLength()) {
  350. return false;
  351. }
  352. if (this.getLineCount() !== other.getLineCount()) {
  353. return false;
  354. }
  355. let offset = 0;
  356. const ret = this.iterate(this.root, node => {
  357. if (node === SENTINEL) {
  358. return true;
  359. }
  360. const str = this.getNodeContent(node);
  361. const len = str.length;
  362. const startPosition = other.nodeAt(offset);
  363. const endPosition = other.nodeAt(offset + len);
  364. const val = other.getValueInRange2(startPosition, endPosition);
  365. offset += len;
  366. return str === val;
  367. });
  368. return ret;
  369. }
  370. public getOffsetAt(lineNumber: number, column: number): number {
  371. let leftLen = 0; // inorder
  372. let x = this.root;
  373. while (x !== SENTINEL) {
  374. if (x.left !== SENTINEL && x.lf_left + 1 >= lineNumber) {
  375. x = x.left;
  376. } else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
  377. leftLen += x.size_left;
  378. // lineNumber >= 2
  379. const accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  380. return (leftLen += accumualtedValInCurrentIndex + column - 1);
  381. } else {
  382. lineNumber -= x.lf_left + x.piece.lineFeedCnt;
  383. leftLen += x.size_left + x.piece.length;
  384. x = x.right;
  385. }
  386. }
  387. return leftLen;
  388. }
  389. public getPositionAt(offset: number): Position {
  390. offset = Math.floor(offset);
  391. offset = Math.max(0, offset);
  392. let x = this.root;
  393. let lfCnt = 0;
  394. const originalOffset = offset;
  395. while (x !== SENTINEL) {
  396. if (x.size_left !== 0 && x.size_left >= offset) {
  397. x = x.left;
  398. } else if (x.size_left + x.piece.length >= offset) {
  399. const out = this.getIndexOf(x, offset - x.size_left);
  400. lfCnt += x.lf_left + out.index;
  401. if (out.index === 0) {
  402. const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
  403. const column = originalOffset - lineStartOffset;
  404. return new Position(lfCnt + 1, column + 1);
  405. }
  406. return new Position(lfCnt + 1, out.remainder + 1);
  407. } else {
  408. offset -= x.size_left + x.piece.length;
  409. lfCnt += x.lf_left + x.piece.lineFeedCnt;
  410. if (x.right === SENTINEL) {
  411. // last node
  412. const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
  413. const column = originalOffset - offset - lineStartOffset;
  414. return new Position(lfCnt + 1, column + 1);
  415. } else {
  416. x = x.right;
  417. }
  418. }
  419. }
  420. return new Position(1, 1);
  421. }
  422. public getValueInRange(range: Range, eol?: string): string {
  423. if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
  424. return '';
  425. }
  426. const startPosition = this.nodeAt2(range.startLineNumber, range.startColumn);
  427. const endPosition = this.nodeAt2(range.endLineNumber, range.endColumn);
  428. const value = this.getValueInRange2(startPosition, endPosition);
  429. if (eol) {
  430. if (eol !== this._EOL || !this._EOLNormalized) {
  431. return value.replace(/\r\n|\r|\n/g, eol);
  432. }
  433. if (eol === this.getEOL() && this._EOLNormalized) {
  434. // if (eol === '\r\n') {}
  435. return value;
  436. }
  437. return value.replace(/\r\n|\r|\n/g, eol);
  438. }
  439. return value;
  440. }
  441. public getValueInRange2(startPosition: NodePosition | null, endPosition: NodePosition | null): string {
  442. if (!startPosition || !endPosition) {
  443. return "";
  444. }
  445. if (startPosition.node === endPosition.node) {
  446. const node = startPosition.node;
  447. const buffer = this._buffers[node.piece.bufferIndex].buffer;
  448. const startOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
  449. return buffer.substring(startOffset + startPosition.remainder, startOffset + endPosition.remainder);
  450. }
  451. let x = startPosition.node;
  452. const buffer = this._buffers[x.piece.bufferIndex].buffer;
  453. const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  454. let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
  455. x = x.next();
  456. while (x !== SENTINEL) {
  457. const buffer = this._buffers[x.piece.bufferIndex].buffer;
  458. const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  459. if (x === endPosition.node) {
  460. ret += buffer.substring(startOffset, startOffset + endPosition.remainder);
  461. break;
  462. } else {
  463. ret += buffer.substr(startOffset, x.piece.length);
  464. }
  465. x = x.next();
  466. }
  467. return ret;
  468. }
  469. public getLinesContent(): string[] {
  470. const lines: string[] = [];
  471. let linesLength = 0;
  472. let currentLine = '';
  473. let danglingCR = false;
  474. this.iterate(this.root, node => {
  475. if (node === SENTINEL) {
  476. return true;
  477. }
  478. const piece = node.piece;
  479. let pieceLength = piece.length;
  480. if (pieceLength === 0) {
  481. return true;
  482. }
  483. const buffer = this._buffers[piece.bufferIndex].buffer;
  484. const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
  485. const pieceStartLine = piece.start.line;
  486. const pieceEndLine = piece.end.line;
  487. let pieceStartOffset = lineStarts[pieceStartLine] + piece.start.column;
  488. if (danglingCR) {
  489. if (buffer.charCodeAt(pieceStartOffset) === CharCode.LineFeed) {
  490. // pretend the \n was in the previous piece..
  491. pieceStartOffset++;
  492. pieceLength--;
  493. }
  494. lines[linesLength++] = currentLine;
  495. currentLine = '';
  496. danglingCR = false;
  497. if (pieceLength === 0) {
  498. return true;
  499. }
  500. }
  501. if (pieceStartLine === pieceEndLine) {
  502. // this piece has no new lines
  503. if (
  504. !this._EOLNormalized &&
  505. buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === CharCode.CarriageReturn
  506. ) {
  507. danglingCR = true;
  508. currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
  509. } else {
  510. currentLine += buffer.substr(pieceStartOffset, pieceLength);
  511. }
  512. return true;
  513. }
  514. // add the text before the first line start in this piece
  515. currentLine += this._EOLNormalized
  516. ? buffer.substring(
  517. pieceStartOffset,
  518. Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - this._EOLLength)
  519. )
  520. : buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, '');
  521. lines[linesLength++] = currentLine;
  522. for (let line = pieceStartLine + 1; line < pieceEndLine; line++) {
  523. currentLine = this._EOLNormalized
  524. ? buffer.substring(lineStarts[line], lineStarts[line + 1] - this._EOLLength)
  525. : buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, '');
  526. lines[linesLength++] = currentLine;
  527. }
  528. if (
  529. !this._EOLNormalized &&
  530. buffer.charCodeAt(lineStarts[pieceEndLine] + piece.end.column - 1) === CharCode.CarriageReturn
  531. ) {
  532. danglingCR = true;
  533. if (piece.end.column === 0) {
  534. // The last line ended with a \r, let's undo the push, it will be pushed by next iteration
  535. linesLength--;
  536. } else {
  537. currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column - 1);
  538. }
  539. } else {
  540. currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column);
  541. }
  542. return true;
  543. });
  544. if (danglingCR) {
  545. lines[linesLength++] = currentLine;
  546. currentLine = '';
  547. }
  548. lines[linesLength++] = currentLine;
  549. return lines;
  550. }
  551. public getLength(): number {
  552. return this._length;
  553. }
  554. public getLineCount(): number {
  555. return this._lineCnt;
  556. }
  557. public getLineContent(lineNumber: number): string {
  558. if (this._lastVisitedLine.lineNumber === lineNumber) {
  559. return this._lastVisitedLine.value;
  560. }
  561. this._lastVisitedLine.lineNumber = lineNumber;
  562. if (lineNumber === this._lineCnt) {
  563. this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
  564. } else if (this._EOLNormalized) {
  565. this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
  566. } else {
  567. this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, '');
  568. }
  569. return this._lastVisitedLine.value;
  570. }
  571. private _getCharCode(nodePos: NodePosition): number {
  572. if (nodePos.remainder === nodePos.node.piece.length) {
  573. // the char we want to fetch is at the head of next node.
  574. const matchingNode = nodePos.node.next();
  575. if (!matchingNode) {
  576. return 0;
  577. }
  578. const buffer = this._buffers[matchingNode.piece.bufferIndex];
  579. const startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
  580. return buffer.buffer.charCodeAt(startOffset);
  581. } else {
  582. const buffer = this._buffers[nodePos.node.piece.bufferIndex];
  583. const startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
  584. const targetOffset = startOffset + nodePos.remainder;
  585. return buffer.buffer.charCodeAt(targetOffset);
  586. }
  587. }
  588. public getLineCharCode(lineNumber: number, index: number): number {
  589. const nodePos = this.nodeAt2(lineNumber, index + 1);
  590. return this._getCharCode(nodePos);
  591. }
  592. public getLineLength(lineNumber: number): number {
  593. if (lineNumber === this.getLineCount()) {
  594. const startOffset = this.getOffsetAt(lineNumber, 1);
  595. return this.getLength() - startOffset;
  596. }
  597. return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;
  598. }
  599. public getCharCode(offset: number): number {
  600. const nodePos = this.nodeAt(offset);
  601. return this._getCharCode(nodePos);
  602. }
  603. public getNearestChunk(offset: number): string {
  604. const nodePos = this.nodeAt(offset);
  605. if (nodePos.remainder === nodePos.node.piece.length) {
  606. // the offset is at the head of next node.
  607. const matchingNode = nodePos.node.next();
  608. if (!matchingNode || matchingNode === SENTINEL) {
  609. return '';
  610. }
  611. const buffer = this._buffers[matchingNode.piece.bufferIndex];
  612. const startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
  613. return buffer.buffer.substring(startOffset, startOffset + matchingNode.piece.length);
  614. } else {
  615. const buffer = this._buffers[nodePos.node.piece.bufferIndex];
  616. const startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
  617. const targetOffset = startOffset + nodePos.remainder;
  618. const targetEnd = startOffset + nodePos.node.piece.length;
  619. return buffer.buffer.substring(targetOffset, targetEnd);
  620. }
  621. }
  622. public findMatchesInNode(
  623. node: TreeNode,
  624. searcher: Searcher,
  625. startLineNumber: number,
  626. startColumn: number,
  627. startCursor: BufferCursor,
  628. endCursor: BufferCursor,
  629. searchData: SearchData,
  630. captureMatches: boolean,
  631. limitResultCount: number,
  632. resultLen: number,
  633. result: FindMatch[]
  634. ) {
  635. const buffer = this._buffers[node.piece.bufferIndex];
  636. const startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
  637. const start = this.offsetInBuffer(node.piece.bufferIndex, startCursor);
  638. const end = this.offsetInBuffer(node.piece.bufferIndex, endCursor);
  639. let m: RegExpExecArray | null;
  640. // Reset regex to search from the beginning
  641. const ret: BufferCursor = { line: 0, column: 0 };
  642. let searchText: string;
  643. let offsetInBuffer: (offset: number) => number;
  644. if (searcher._wordSeparators) {
  645. searchText = buffer.buffer.substring(start, end);
  646. offsetInBuffer = (offset: number) => offset + start;
  647. searcher.reset(0);
  648. } else {
  649. searchText = buffer.buffer;
  650. offsetInBuffer = (offset: number) => offset;
  651. searcher.reset(start);
  652. }
  653. do {
  654. m = searcher.next(searchText);
  655. if (m) {
  656. if (offsetInBuffer(m.index) >= end) {
  657. return resultLen;
  658. }
  659. this.positionInBuffer(node, offsetInBuffer(m.index) - startOffsetInBuffer, ret);
  660. const lineFeedCnt = this.getLineFeedCnt(node.piece.bufferIndex, startCursor, ret);
  661. const retStartColumn =
  662. ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
  663. const retEndColumn = retStartColumn + m[0].length;
  664. result[resultLen++] = createFindMatch(
  665. new Range(
  666. startLineNumber + lineFeedCnt,
  667. retStartColumn,
  668. startLineNumber + lineFeedCnt,
  669. retEndColumn
  670. ),
  671. m,
  672. captureMatches
  673. );
  674. if (offsetInBuffer(m.index) + m[0].length >= end) {
  675. return resultLen;
  676. }
  677. if (resultLen >= limitResultCount) {
  678. return resultLen;
  679. }
  680. }
  681. } while (m);
  682. return resultLen;
  683. }
  684. public findMatchesLineByLine(
  685. searchRange: Range,
  686. searchData: SearchData,
  687. captureMatches: boolean,
  688. limitResultCount: number
  689. ): FindMatch[] {
  690. const result: FindMatch[] = [];
  691. let resultLen = 0;
  692. const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
  693. let startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn);
  694. if (startPosition === null) {
  695. return [];
  696. }
  697. const endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);
  698. if (endPosition === null) {
  699. return [];
  700. }
  701. let start = this.positionInBuffer(startPosition.node, startPosition.remainder);
  702. const end = this.positionInBuffer(endPosition.node, endPosition.remainder);
  703. if (startPosition.node === endPosition.node) {
  704. this.findMatchesInNode(
  705. startPosition.node,
  706. searcher,
  707. searchRange.startLineNumber,
  708. searchRange.startColumn,
  709. start,
  710. end,
  711. searchData,
  712. captureMatches,
  713. limitResultCount,
  714. resultLen,
  715. result
  716. );
  717. return result;
  718. }
  719. let startLineNumber = searchRange.startLineNumber;
  720. let currentNode = startPosition.node;
  721. while (currentNode !== endPosition.node) {
  722. const lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end);
  723. if (lineBreakCnt >= 1) {
  724. // last line break position
  725. const lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;
  726. const startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);
  727. const nextLineStartOffset = lineStarts[start.line + lineBreakCnt];
  728. const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
  729. resultLen = this.findMatchesInNode(
  730. currentNode,
  731. searcher,
  732. startLineNumber,
  733. startColumn,
  734. start,
  735. this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer),
  736. searchData,
  737. captureMatches,
  738. limitResultCount,
  739. resultLen,
  740. result
  741. );
  742. if (resultLen >= limitResultCount) {
  743. return result;
  744. }
  745. startLineNumber += lineBreakCnt;
  746. }
  747. const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
  748. // search for the remaining content
  749. if (startLineNumber === searchRange.endLineNumber) {
  750. const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1);
  751. resultLen = this._findMatchesInLine(
  752. searchData,
  753. searcher,
  754. text,
  755. searchRange.endLineNumber,
  756. startColumn,
  757. resultLen,
  758. result,
  759. captureMatches,
  760. limitResultCount
  761. );
  762. return result;
  763. }
  764. resultLen = this._findMatchesInLine(
  765. searchData,
  766. searcher,
  767. this.getLineContent(startLineNumber).substr(startColumn),
  768. startLineNumber,
  769. startColumn,
  770. resultLen,
  771. result,
  772. captureMatches,
  773. limitResultCount
  774. );
  775. if (resultLen >= limitResultCount) {
  776. return result;
  777. }
  778. startLineNumber++;
  779. startPosition = this.nodeAt2(startLineNumber, 1);
  780. currentNode = startPosition.node;
  781. start = this.positionInBuffer(startPosition.node, startPosition.remainder);
  782. }
  783. if (startLineNumber === searchRange.endLineNumber) {
  784. const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
  785. const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1);
  786. resultLen = this._findMatchesInLine(
  787. searchData,
  788. searcher,
  789. text,
  790. searchRange.endLineNumber,
  791. startColumn,
  792. resultLen,
  793. result,
  794. captureMatches,
  795. limitResultCount
  796. );
  797. return result;
  798. }
  799. const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
  800. resultLen = this.findMatchesInNode(
  801. endPosition.node,
  802. searcher,
  803. startLineNumber,
  804. startColumn,
  805. start,
  806. end,
  807. searchData,
  808. captureMatches,
  809. limitResultCount,
  810. resultLen,
  811. result
  812. );
  813. return result;
  814. }
  815. private _findMatchesInLine(
  816. searchData: SearchData,
  817. searcher: Searcher,
  818. text: string,
  819. lineNumber: number,
  820. deltaOffset: number,
  821. resultLen: number,
  822. result: FindMatch[],
  823. captureMatches: boolean,
  824. limitResultCount: number
  825. ): number {
  826. const wordSeparators = searchData.wordSeparators;
  827. if (!captureMatches && searchData.simpleSearch) {
  828. const searchString = searchData.simpleSearch;
  829. const searchStringLen = searchString.length;
  830. const textLength = text.length;
  831. let lastMatchIndex = -searchStringLen;
  832. while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
  833. if (
  834. !wordSeparators ||
  835. isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)
  836. ) {
  837. result[resultLen++] = new FindMatch(
  838. new Range(
  839. lineNumber,
  840. lastMatchIndex + 1 + deltaOffset,
  841. lineNumber,
  842. lastMatchIndex + 1 + searchStringLen + deltaOffset
  843. ),
  844. null
  845. );
  846. if (resultLen >= limitResultCount) {
  847. return resultLen;
  848. }
  849. }
  850. }
  851. return resultLen;
  852. }
  853. let m: RegExpExecArray | null;
  854. // Reset regex to search from the beginning
  855. searcher.reset(0);
  856. do {
  857. m = searcher.next(text);
  858. if (m) {
  859. result[resultLen++] = createFindMatch(
  860. new Range(
  861. lineNumber,
  862. m.index + 1 + deltaOffset,
  863. lineNumber,
  864. m.index + 1 + m[0].length + deltaOffset
  865. ),
  866. m,
  867. captureMatches
  868. );
  869. if (resultLen >= limitResultCount) {
  870. return resultLen;
  871. }
  872. }
  873. } while (m);
  874. return resultLen;
  875. }
  876. // #endregion
  877. // #region Piece Table
  878. public insert(offset: number, value: string, eolNormalized: boolean = false): void {
  879. this._EOLNormalized = this._EOLNormalized && eolNormalized;
  880. this._lastVisitedLine.lineNumber = 0;
  881. this._lastVisitedLine.value = '';
  882. if (this.root !== SENTINEL) {
  883. const { node, remainder, nodeStartOffset } = this.nodeAt(offset);
  884. const piece = node.piece;
  885. const bufferIndex = piece.bufferIndex;
  886. const insertPosInBuffer = this.positionInBuffer(node, remainder);
  887. if (
  888. node.piece.bufferIndex === 0 &&
  889. piece.end.line === this._lastChangeBufferPos.line &&
  890. piece.end.column === this._lastChangeBufferPos.column &&
  891. nodeStartOffset + piece.length === offset &&
  892. value.length < AverageBufferSize
  893. ) {
  894. // changed buffer
  895. this.appendToNode(node, value);
  896. this.computeBufferMetadata();
  897. return;
  898. }
  899. if (nodeStartOffset === offset) {
  900. this.insertContentToNodeLeft(value, node);
  901. this._searchCache.validate(offset);
  902. } else if (nodeStartOffset + node.piece.length > offset) {
  903. // we are inserting into the middle of a node.
  904. const nodesToDel: TreeNode[] = [];
  905. let newRightPiece = new Piece(
  906. piece.bufferIndex,
  907. insertPosInBuffer,
  908. piece.end,
  909. this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end),
  910. this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer)
  911. );
  912. if (this.shouldCheckCRLF() && this.endWithCR(value)) {
  913. const headOfRight = this.nodeCharCodeAt(node, remainder);
  914. if (headOfRight === 10 /** \n */) {
  915. const newStart: BufferCursor = {
  916. line: newRightPiece.start.line + 1,
  917. column: 0,
  918. };
  919. newRightPiece = new Piece(
  920. newRightPiece.bufferIndex,
  921. newStart,
  922. newRightPiece.end,
  923. this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end),
  924. newRightPiece.length - 1
  925. );
  926. value += '\n';
  927. }
  928. }
  929. // reuse node for content before insertion point.
  930. if (this.shouldCheckCRLF() && this.startWithLF(value)) {
  931. const tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
  932. if (tailOfLeft === 13 /** \r */) {
  933. const previousPos = this.positionInBuffer(node, remainder - 1);
  934. this.deleteNodeTail(node, previousPos);
  935. value = '\r' + value;
  936. if (node.piece.length === 0) {
  937. nodesToDel.push(node);
  938. }
  939. } else {
  940. this.deleteNodeTail(node, insertPosInBuffer);
  941. }
  942. } else {
  943. this.deleteNodeTail(node, insertPosInBuffer);
  944. }
  945. const newPieces = this.createNewPieces(value);
  946. if (newRightPiece.length > 0) {
  947. this.rbInsertRight(node, newRightPiece);
  948. }
  949. let tmpNode = node;
  950. for (let k = 0; k < newPieces.length; k++) {
  951. tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
  952. }
  953. this.deleteNodes(nodesToDel);
  954. } else {
  955. this.insertContentToNodeRight(value, node);
  956. }
  957. } else {
  958. // insert new node
  959. const pieces = this.createNewPieces(value);
  960. let node = this.rbInsertLeft(null, pieces[0]);
  961. for (let k = 1; k < pieces.length; k++) {
  962. node = this.rbInsertRight(node, pieces[k]);
  963. }
  964. }
  965. // todo, this is too brutal. Total line feed count should be updated the same way as lf_left.
  966. this.computeBufferMetadata();
  967. }
  968. public delete(offset: number, cnt: number): void {
  969. this._lastVisitedLine.lineNumber = 0;
  970. this._lastVisitedLine.value = '';
  971. if (cnt <= 0 || this.root === SENTINEL) {
  972. return;
  973. }
  974. const startPosition = this.nodeAt(offset);
  975. const endPosition = this.nodeAt(offset + cnt);
  976. const startNode = startPosition.node;
  977. const endNode = endPosition.node;
  978. if (startNode === endNode) {
  979. const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
  980. const endSplitPosInBuffer = this.positionInBuffer(startNode, endPosition.remainder);
  981. if (startPosition.nodeStartOffset === offset) {
  982. if (cnt === startNode.piece.length) {
  983. // delete node
  984. const next = startNode.next();
  985. rbDelete(this, startNode);
  986. this.validateCRLFWithPrevNode(next);
  987. this.computeBufferMetadata();
  988. return;
  989. }
  990. this.deleteNodeHead(startNode, endSplitPosInBuffer);
  991. this._searchCache.validate(offset);
  992. this.validateCRLFWithPrevNode(startNode);
  993. this.computeBufferMetadata();
  994. return;
  995. }
  996. if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
  997. this.deleteNodeTail(startNode, startSplitPosInBuffer);
  998. this.validateCRLFWithNextNode(startNode);
  999. this.computeBufferMetadata();
  1000. return;
  1001. }
  1002. // delete content in the middle, this node will be splitted to nodes
  1003. this.shrinkNode(startNode, startSplitPosInBuffer, endSplitPosInBuffer);
  1004. this.computeBufferMetadata();
  1005. return;
  1006. }
  1007. const nodesToDel: TreeNode[] = [];
  1008. const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
  1009. this.deleteNodeTail(startNode, startSplitPosInBuffer);
  1010. this._searchCache.validate(offset);
  1011. if (startNode.piece.length === 0) {
  1012. nodesToDel.push(startNode);
  1013. }
  1014. // update last touched node
  1015. const endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
  1016. this.deleteNodeHead(endNode, endSplitPosInBuffer);
  1017. if (endNode.piece.length === 0) {
  1018. nodesToDel.push(endNode);
  1019. }
  1020. // delete nodes in between
  1021. const secondNode = startNode.next();
  1022. for (let node = secondNode; node !== SENTINEL && node !== endNode; node = node.next()) {
  1023. nodesToDel.push(node);
  1024. }
  1025. const prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
  1026. this.deleteNodes(nodesToDel);
  1027. this.validateCRLFWithNextNode(prev);
  1028. this.computeBufferMetadata();
  1029. }
  1030. private insertContentToNodeLeft(value: string, node: TreeNode) {
  1031. // we are inserting content to the beginning of node
  1032. const nodesToDel: TreeNode[] = [];
  1033. if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
  1034. // move `\n` to new node.
  1035. const piece = node.piece;
  1036. const newStart: BufferCursor = { line: piece.start.line + 1, column: 0 };
  1037. const nPiece = new Piece(
  1038. piece.bufferIndex,
  1039. newStart,
  1040. piece.end,
  1041. this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end),
  1042. piece.length - 1
  1043. );
  1044. node.piece = nPiece;
  1045. value += '\n';
  1046. updateTreeMetadata(this, node, -1, -1);
  1047. if (node.piece.length === 0) {
  1048. nodesToDel.push(node);
  1049. }
  1050. }
  1051. const newPieces = this.createNewPieces(value);
  1052. let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);
  1053. for (let k = newPieces.length - 2; k >= 0; k--) {
  1054. newNode = this.rbInsertLeft(newNode, newPieces[k]);
  1055. }
  1056. this.validateCRLFWithPrevNode(newNode);
  1057. this.deleteNodes(nodesToDel);
  1058. }
  1059. private insertContentToNodeRight(value: string, node: TreeNode) {
  1060. // we are inserting to the right of this node.
  1061. if (this.adjustCarriageReturnFromNext(value, node)) {
  1062. // move \n to the new node.
  1063. value += '\n';
  1064. }
  1065. const newPieces = this.createNewPieces(value);
  1066. const newNode = this.rbInsertRight(node, newPieces[0]);
  1067. let tmpNode = newNode;
  1068. for (let k = 1; k < newPieces.length; k++) {
  1069. tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
  1070. }
  1071. this.validateCRLFWithPrevNode(newNode);
  1072. }
  1073. private positionInBuffer(node: TreeNode, remainder: number): BufferCursor;
  1074. private positionInBuffer(node: TreeNode, remainder: number, ret: BufferCursor): null;
  1075. private positionInBuffer(node: TreeNode, remainder: number, ret?: BufferCursor): BufferCursor | null {
  1076. const piece = node.piece;
  1077. const bufferIndex = node.piece.bufferIndex;
  1078. const lineStarts = this._buffers[bufferIndex].lineStarts;
  1079. const startOffset = lineStarts[piece.start.line] + piece.start.column;
  1080. const offset = startOffset + remainder;
  1081. // binary search offset between startOffset and endOffset
  1082. let low = piece.start.line;
  1083. let high = piece.end.line;
  1084. let mid: number = 0;
  1085. let midStop: number = 0;
  1086. let midStart: number = 0;
  1087. while (low <= high) {
  1088. mid = (low + (high - low) / 2) | 0;
  1089. midStart = lineStarts[mid];
  1090. if (mid === high) {
  1091. break;
  1092. }
  1093. midStop = lineStarts[mid + 1];
  1094. if (offset < midStart) {
  1095. high = mid - 1;
  1096. } else if (offset >= midStop) {
  1097. low = mid + 1;
  1098. } else {
  1099. break;
  1100. }
  1101. }
  1102. if (ret) {
  1103. ret.line = mid;
  1104. ret.column = offset - midStart;
  1105. return null;
  1106. }
  1107. return {
  1108. line: mid,
  1109. column: offset - midStart,
  1110. };
  1111. }
  1112. private getLineFeedCnt(bufferIndex: number, start: BufferCursor, end: BufferCursor): number {
  1113. // we don't need to worry about start: abc\r|\n, or abc|\r, or abc|\n, or abc|\r\n doesn't change the fact that, there is one line break after start.
  1114. // now let's take care of end: abc\r|\n, if end is in between \r and \n, we need to add line feed count by 1
  1115. if (end.column === 0) {
  1116. return end.line - start.line;
  1117. }
  1118. const lineStarts = this._buffers[bufferIndex].lineStarts;
  1119. if (end.line === lineStarts.length - 1) {
  1120. // it means, there is no \n after end, otherwise, there will be one more lineStart.
  1121. return end.line - start.line;
  1122. }
  1123. const nextLineStartOffset = lineStarts[end.line + 1];
  1124. const endOffset = lineStarts[end.line] + end.column;
  1125. if (nextLineStartOffset > endOffset + 1) {
  1126. // there are more than 1 character after end, which means it can't be \n
  1127. return end.line - start.line;
  1128. }
  1129. // endOffset + 1 === nextLineStartOffset
  1130. // character at endOffset is \n, so we check the character before first
  1131. // if character at endOffset is \r, end.column is 0 and we can't get here.
  1132. const previousCharOffset = endOffset - 1; // end.column > 0 so it's okay.
  1133. const buffer = this._buffers[bufferIndex].buffer;
  1134. if (buffer.charCodeAt(previousCharOffset) === 13) {
  1135. return end.line - start.line + 1;
  1136. } else {
  1137. return end.line - start.line;
  1138. }
  1139. }
  1140. private offsetInBuffer(bufferIndex: number, cursor: BufferCursor): number {
  1141. const lineStarts = this._buffers[bufferIndex].lineStarts;
  1142. return lineStarts[cursor.line] + cursor.column;
  1143. }
  1144. private deleteNodes(nodes: TreeNode[]): void {
  1145. for (let i = 0; i < nodes.length; i++) {
  1146. rbDelete(this, nodes[i]);
  1147. }
  1148. }
  1149. private createNewPieces(text: string): Piece[] {
  1150. if (text.length > AverageBufferSize) {
  1151. // the content is large, operations like substring, charCode becomes slow
  1152. // so here we split it into smaller chunks, just like what we did for CR/LF normalization
  1153. const newPieces: Piece[] = [];
  1154. while (text.length > AverageBufferSize) {
  1155. const lastChar = text.charCodeAt(AverageBufferSize - 1);
  1156. let splitText;
  1157. if (lastChar === CharCode.CarriageReturn || (lastChar >= 0xd800 && lastChar <= 0xdbff)) {
  1158. // last character is \r or a high surrogate => keep it back
  1159. splitText = text.substring(0, AverageBufferSize - 1);
  1160. text = text.substring(AverageBufferSize - 1);
  1161. } else {
  1162. splitText = text.substring(0, AverageBufferSize);
  1163. text = text.substring(AverageBufferSize);
  1164. }
  1165. const lineStarts = createLineStartsFast(splitText);
  1166. newPieces.push(
  1167. new Piece(
  1168. this._buffers.length /* buffer index */,
  1169. { line: 0, column: 0 },
  1170. {
  1171. line: lineStarts.length - 1,
  1172. column: splitText.length - lineStarts[lineStarts.length - 1],
  1173. },
  1174. lineStarts.length - 1,
  1175. splitText.length
  1176. )
  1177. );
  1178. this._buffers.push(new StringBuffer(splitText, lineStarts));
  1179. }
  1180. const lineStarts = createLineStartsFast(text);
  1181. newPieces.push(
  1182. new Piece(
  1183. this._buffers.length /* buffer index */,
  1184. { line: 0, column: 0 },
  1185. {
  1186. line: lineStarts.length - 1,
  1187. column: text.length - lineStarts[lineStarts.length - 1],
  1188. },
  1189. lineStarts.length - 1,
  1190. text.length
  1191. )
  1192. );
  1193. this._buffers.push(new StringBuffer(text, lineStarts));
  1194. return newPieces;
  1195. }
  1196. let startOffset = this._buffers[0].buffer.length;
  1197. const lineStarts = createLineStartsFast(text, false);
  1198. let start = this._lastChangeBufferPos;
  1199. if (
  1200. this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset &&
  1201. startOffset !== 0 &&
  1202. this.startWithLF(text) &&
  1203. this.endWithCR(this._buffers[0].buffer) // todo, we can check this._lastChangeBufferPos's column as it's the last one
  1204. ) {
  1205. this._lastChangeBufferPos = {
  1206. line: this._lastChangeBufferPos.line,
  1207. column: this._lastChangeBufferPos.column + 1,
  1208. };
  1209. start = this._lastChangeBufferPos;
  1210. for (let i = 0; i < lineStarts.length; i++) {
  1211. lineStarts[i] += startOffset + 1;
  1212. }
  1213. this._buffers[0].lineStarts = (<number[]> this._buffers[0].lineStarts).concat(<number[]>lineStarts.slice(1));
  1214. this._buffers[0].buffer += '_' + text;
  1215. startOffset += 1;
  1216. } else {
  1217. if (startOffset !== 0) {
  1218. for (let i = 0; i < lineStarts.length; i++) {
  1219. lineStarts[i] += startOffset;
  1220. }
  1221. }
  1222. this._buffers[0].lineStarts = (<number[]> this._buffers[0].lineStarts).concat(<number[]>lineStarts.slice(1));
  1223. this._buffers[0].buffer += text;
  1224. }
  1225. const endOffset = this._buffers[0].buffer.length;
  1226. const endIndex = this._buffers[0].lineStarts.length - 1;
  1227. const endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
  1228. const endPos = { line: endIndex, column: endColumn };
  1229. const newPiece = new Piece(
  1230. 0 /** todo@peng */,
  1231. start,
  1232. endPos,
  1233. this.getLineFeedCnt(0, start, endPos),
  1234. endOffset - startOffset
  1235. );
  1236. this._lastChangeBufferPos = endPos;
  1237. return [newPiece];
  1238. }
  1239. public getLinesRawContent(): string {
  1240. return this.getContentOfSubTree(this.root);
  1241. }
  1242. public getLineRawContent(lineNumber: number, endOffset: number = 0): string {
  1243. let x = this.root;
  1244. let ret = '';
  1245. const cache = this._searchCache.get2(lineNumber);
  1246. if (cache) {
  1247. x = cache.node;
  1248. const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);
  1249. const buffer = this._buffers[x.piece.bufferIndex].buffer;
  1250. const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  1251. if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
  1252. ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
  1253. } else {
  1254. const accumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber);
  1255. return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
  1256. }
  1257. } else {
  1258. let nodeStartOffset = 0;
  1259. const originalLineNumber = lineNumber;
  1260. while (x !== SENTINEL) {
  1261. if (x.left !== SENTINEL && x.lf_left >= lineNumber - 1) {
  1262. x = x.left;
  1263. } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
  1264. const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  1265. const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
  1266. const buffer = this._buffers[x.piece.bufferIndex].buffer;
  1267. const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  1268. nodeStartOffset += x.size_left;
  1269. this._searchCache.set({
  1270. node: x,
  1271. nodeStartOffset,
  1272. nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left),
  1273. });
  1274. return buffer.substring(
  1275. startOffset + prevAccumulatedValue,
  1276. startOffset + accumulatedValue - endOffset
  1277. );
  1278. } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
  1279. const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  1280. const buffer = this._buffers[x.piece.bufferIndex].buffer;
  1281. const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  1282. ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
  1283. break;
  1284. } else {
  1285. lineNumber -= x.lf_left + x.piece.lineFeedCnt;
  1286. nodeStartOffset += x.size_left + x.piece.length;
  1287. x = x.right;
  1288. }
  1289. }
  1290. }
  1291. // search in order, to find the node contains end column
  1292. x = x.next();
  1293. while (x !== SENTINEL) {
  1294. const buffer = this._buffers[x.piece.bufferIndex].buffer;
  1295. if (x.piece.lineFeedCnt > 0) {
  1296. const accumulatedValue = this.getAccumulatedValue(x, 0);
  1297. const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  1298. ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
  1299. return ret;
  1300. } else {
  1301. const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
  1302. ret += buffer.substr(startOffset, x.piece.length);
  1303. }
  1304. x = x.next();
  1305. }
  1306. return ret;
  1307. }
  1308. private computeBufferMetadata() {
  1309. let x = this.root;
  1310. let lfCnt = 1;
  1311. let len = 0;
  1312. while (x !== SENTINEL) {
  1313. lfCnt += x.lf_left + x.piece.lineFeedCnt;
  1314. len += x.size_left + x.piece.length;
  1315. x = x.right;
  1316. }
  1317. this._lineCnt = lfCnt;
  1318. this._length = len;
  1319. this._searchCache.validate(this._length);
  1320. }
  1321. // #region node operations
  1322. private getIndexOf(node: TreeNode, accumulatedValue: number): { index: number; remainder: number } {
  1323. const piece = node.piece;
  1324. const pos = this.positionInBuffer(node, accumulatedValue);
  1325. const lineCnt = pos.line - piece.start.line;
  1326. if (
  1327. this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) ===
  1328. accumulatedValue
  1329. ) {
  1330. // we are checking the end of this node, so a CRLF check is necessary.
  1331. const realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);
  1332. if (realLineCnt !== lineCnt) {
  1333. // aha yes, CRLF
  1334. return { index: realLineCnt, remainder: 0 };
  1335. }
  1336. }
  1337. return { index: lineCnt, remainder: pos.column };
  1338. }
  1339. private getAccumulatedValue(node: TreeNode, index: number) {
  1340. if (index < 0) {
  1341. return 0;
  1342. }
  1343. const piece = node.piece;
  1344. const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
  1345. const expectedLineStartIndex = piece.start.line + index + 1;
  1346. if (expectedLineStartIndex > piece.end.line) {
  1347. return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
  1348. } else {
  1349. return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
  1350. }
  1351. }
  1352. private deleteNodeTail(node: TreeNode, pos: BufferCursor) {
  1353. const piece = node.piece;
  1354. const originalLFCnt = piece.lineFeedCnt;
  1355. const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
  1356. const newEnd = pos;
  1357. const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
  1358. const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
  1359. const lf_delta = newLineFeedCnt - originalLFCnt;
  1360. const size_delta = newEndOffset - originalEndOffset;
  1361. const newLength = piece.length + size_delta;
  1362. node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
  1363. updateTreeMetadata(this, node, size_delta, lf_delta);
  1364. }
  1365. private deleteNodeHead(node: TreeNode, pos: BufferCursor) {
  1366. const piece = node.piece;
  1367. const originalLFCnt = piece.lineFeedCnt;
  1368. const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
  1369. const newStart = pos;
  1370. const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
  1371. const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
  1372. const lf_delta = newLineFeedCnt - originalLFCnt;
  1373. const size_delta = originalStartOffset - newStartOffset;
  1374. const newLength = piece.length + size_delta;
  1375. node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
  1376. updateTreeMetadata(this, node, size_delta, lf_delta);
  1377. }
  1378. private shrinkNode(node: TreeNode, start: BufferCursor, end: BufferCursor) {
  1379. const piece = node.piece;
  1380. const originalStartPos = piece.start;
  1381. const originalEndPos = piece.end;
  1382. // old piece, originalStartPos, start
  1383. const oldLength = piece.length;
  1384. const oldLFCnt = piece.lineFeedCnt;
  1385. const newEnd = start;
  1386. const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
  1387. const newLength =
  1388. this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
  1389. node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
  1390. updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
  1391. // new right piece, end, originalEndPos
  1392. const newPiece = new Piece(
  1393. piece.bufferIndex,
  1394. end,
  1395. originalEndPos,
  1396. this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos),
  1397. this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end)
  1398. );
  1399. const newNode = this.rbInsertRight(node, newPiece);
  1400. this.validateCRLFWithPrevNode(newNode);
  1401. }
  1402. private appendToNode(node: TreeNode, value: string): void {
  1403. if (this.adjustCarriageReturnFromNext(value, node)) {
  1404. value += '\n';
  1405. }
  1406. const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);
  1407. const startOffset = this._buffers[0].buffer.length;
  1408. this._buffers[0].buffer += value;
  1409. const lineStarts = createLineStartsFast(value, false);
  1410. for (let i = 0; i < lineStarts.length; i++) {
  1411. lineStarts[i] += startOffset;
  1412. }
  1413. if (hitCRLF) {
  1414. const prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
  1415. (<number[]> this._buffers[0].lineStarts).pop();
  1416. // _lastChangeBufferPos is already wrong
  1417. this._lastChangeBufferPos = {
  1418. line: this._lastChangeBufferPos.line - 1,
  1419. column: startOffset - prevStartOffset,
  1420. };
  1421. }
  1422. this._buffers[0].lineStarts = (<number[]> this._buffers[0].lineStarts).concat(<number[]>lineStarts.slice(1));
  1423. const endIndex = this._buffers[0].lineStarts.length - 1;
  1424. const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
  1425. const newEnd = { line: endIndex, column: endColumn };
  1426. const newLength = node.piece.length + value.length;
  1427. const oldLineFeedCnt = node.piece.lineFeedCnt;
  1428. const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);
  1429. const lf_delta = newLineFeedCnt - oldLineFeedCnt;
  1430. node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
  1431. this._lastChangeBufferPos = newEnd;
  1432. updateTreeMetadata(this, node, value.length, lf_delta);
  1433. }
  1434. private nodeAt(offset: number): NodePosition {
  1435. let x = this.root;
  1436. const cache = this._searchCache.get(offset);
  1437. if (cache) {
  1438. return {
  1439. node: cache.node,
  1440. nodeStartOffset: cache.nodeStartOffset,
  1441. remainder: offset - cache.nodeStartOffset,
  1442. };
  1443. }
  1444. let nodeStartOffset = 0;
  1445. while (x !== SENTINEL) {
  1446. if (x.size_left > offset) {
  1447. x = x.left;
  1448. } else if (x.size_left + x.piece.length >= offset) {
  1449. nodeStartOffset += x.size_left;
  1450. const ret = {
  1451. node: x,
  1452. remainder: offset - x.size_left,
  1453. nodeStartOffset,
  1454. };
  1455. this._searchCache.set(ret);
  1456. return ret;
  1457. } else {
  1458. offset -= x.size_left + x.piece.length;
  1459. nodeStartOffset += x.size_left + x.piece.length;
  1460. x = x.right;
  1461. }
  1462. }
  1463. return null!;
  1464. }
  1465. private nodeAt2(lineNumber: number, column: number): NodePosition {
  1466. let x = this.root;
  1467. let nodeStartOffset = 0;
  1468. while (x !== SENTINEL) {
  1469. if (x.left !== SENTINEL && x.lf_left >= lineNumber - 1) {
  1470. x = x.left;
  1471. } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
  1472. const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  1473. const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
  1474. nodeStartOffset += x.size_left;
  1475. return {
  1476. node: x,
  1477. remainder: Math.min(prevAccumualtedValue + column - 1, accumulatedValue),
  1478. nodeStartOffset,
  1479. };
  1480. } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
  1481. const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
  1482. if (prevAccumualtedValue + column - 1 <= x.piece.length) {
  1483. return {
  1484. node: x,
  1485. remainder: prevAccumualtedValue + column - 1,
  1486. nodeStartOffset,
  1487. };
  1488. } else {
  1489. column -= x.piece.length - prevAccumualtedValue;
  1490. break;
  1491. }
  1492. } else {
  1493. lineNumber -= x.lf_left + x.piece.lineFeedCnt;
  1494. nodeStartOffset += x.size_left + x.piece.length;
  1495. x = x.right;
  1496. }
  1497. }
  1498. // search in order, to find the node contains position.column
  1499. x = x.next();
  1500. while (x !== SENTINEL) {
  1501. if (x.piece.lineFeedCnt > 0) {
  1502. const accumulatedValue = this.getAccumulatedValue(x, 0);
  1503. const nodeStartOffset = this.offsetOfNode(x);
  1504. return {
  1505. node: x,
  1506. remainder: Math.min(column - 1, accumulatedValue),
  1507. nodeStartOffset,
  1508. };
  1509. } else {
  1510. if (x.piece.length >= column - 1) {
  1511. const nodeStartOffset = this.offsetOfNode(x);
  1512. return {
  1513. node: x,
  1514. remainder: column - 1,
  1515. nodeStartOffset,
  1516. };
  1517. } else {
  1518. column -= x.piece.length;
  1519. }
  1520. }
  1521. x = x.next();
  1522. }
  1523. return null!;
  1524. }
  1525. private nodeCharCodeAt(node: TreeNode, offset: number): number {
  1526. if (node.piece.lineFeedCnt < 1) {
  1527. return -1;
  1528. }
  1529. const buffer = this._buffers[node.piece.bufferIndex];
  1530. const newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset;
  1531. return buffer.buffer.charCodeAt(newOffset);
  1532. }
  1533. private offsetOfNode(node: TreeNode): number {
  1534. if (!node) {
  1535. return 0;
  1536. }
  1537. let pos = node.size_left;
  1538. while (node !== this.root) {
  1539. if (node.parent.right === node) {
  1540. pos += node.parent.size_left + node.parent.piece.length;
  1541. }
  1542. node = node.parent;
  1543. }
  1544. return pos;
  1545. }
  1546. // #endregion
  1547. // #region CRLF
  1548. private shouldCheckCRLF() {
  1549. return !(this._EOLNormalized && this._EOL === '\n');
  1550. }
  1551. private startWithLF(val: string | TreeNode): boolean {
  1552. if (typeof val === 'string') {
  1553. return val.charCodeAt(0) === 10;
  1554. }
  1555. if (val === SENTINEL || val.piece.lineFeedCnt === 0) {
  1556. return false;
  1557. }
  1558. const piece = val.piece;
  1559. const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
  1560. const line = piece.start.line;
  1561. const startOffset = lineStarts[line] + piece.start.column;
  1562. if (line === lineStarts.length - 1) {
  1563. // last line, so there is no line feed at the end of this line
  1564. return false;
  1565. }
  1566. const nextLineOffset = lineStarts[line + 1];
  1567. if (nextLineOffset > startOffset + 1) {
  1568. return false;
  1569. }
  1570. return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
  1571. }
  1572. private endWithCR(val: string | TreeNode): boolean {
  1573. if (typeof val === 'string') {
  1574. return val.charCodeAt(val.length - 1) === 13;
  1575. }
  1576. if (val === SENTINEL || val.piece.lineFeedCnt === 0) {
  1577. return false;
  1578. }
  1579. return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
  1580. }
  1581. private validateCRLFWithPrevNode(nextNode: TreeNode) {
  1582. if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
  1583. const node = nextNode.prev();
  1584. if (this.endWithCR(node)) {
  1585. this.fixCRLF(node, nextNode);
  1586. }
  1587. }
  1588. }
  1589. private validateCRLFWithNextNode(node: TreeNode) {
  1590. if (this.shouldCheckCRLF() && this.endWithCR(node)) {
  1591. const nextNode = node.next();
  1592. if (this.startWithLF(nextNode)) {
  1593. this.fixCRLF(node, nextNode);
  1594. }
  1595. }
  1596. }
  1597. private fixCRLF(prev: TreeNode, next: TreeNode) {
  1598. const nodesToDel: TreeNode[] = [];
  1599. // update node
  1600. const lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
  1601. let newEnd: BufferCursor;
  1602. if (prev.piece.end.column === 0) {
  1603. // it means, last line ends with \r, not \r\n
  1604. newEnd = {
  1605. line: prev.piece.end.line - 1,
  1606. column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1,
  1607. };
  1608. } else {
  1609. // \r\n
  1610. newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };
  1611. }
  1612. const prevNewLength = prev.piece.length - 1;
  1613. const prevNewLFCnt = prev.piece.lineFeedCnt - 1;
  1614. prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
  1615. updateTreeMetadata(this, prev, -1, -1);
  1616. if (prev.piece.length === 0) {
  1617. nodesToDel.push(prev);
  1618. }
  1619. // update nextNode
  1620. const newStart: BufferCursor = {
  1621. line: next.piece.start.line + 1,
  1622. column: 0,
  1623. };
  1624. const newLength = next.piece.length - 1;
  1625. const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
  1626. next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
  1627. updateTreeMetadata(this, next, -1, -1);
  1628. if (next.piece.length === 0) {
  1629. nodesToDel.push(next);
  1630. }
  1631. // create new piece which contains \r\n
  1632. const pieces = this.createNewPieces('\r\n');
  1633. this.rbInsertRight(prev, pieces[0]);
  1634. // delete empty nodes
  1635. for (let i = 0; i < nodesToDel.length; i++) {
  1636. rbDelete(this, nodesToDel[i]);
  1637. }
  1638. }
  1639. private adjustCarriageReturnFromNext(value: string, node: TreeNode): boolean {
  1640. if (this.shouldCheckCRLF() && this.endWithCR(value)) {
  1641. const nextNode = node.next();
  1642. if (this.startWithLF(nextNode)) {
  1643. // move `\n` forward
  1644. value += '\n';
  1645. if (nextNode.piece.length === 1) {
  1646. rbDelete(this, nextNode);
  1647. } else {
  1648. const piece = nextNode.piece;
  1649. const newStart: BufferCursor = {
  1650. line: piece.start.line + 1,
  1651. column: 0,
  1652. };
  1653. const newLength = piece.length - 1;
  1654. const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
  1655. nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
  1656. updateTreeMetadata(this, nextNode, -1, -1);
  1657. }
  1658. return true;
  1659. }
  1660. }
  1661. return false;
  1662. }
  1663. // #endregion
  1664. // #endregion
  1665. // #region Tree operations
  1666. iterate(node: TreeNode, callback: (node: TreeNode) => boolean): boolean {
  1667. if (node === SENTINEL) {
  1668. return callback(SENTINEL);
  1669. }
  1670. const leftRet = this.iterate(node.left, callback);
  1671. if (!leftRet) {
  1672. return leftRet;
  1673. }
  1674. return callback(node) && this.iterate(node.right, callback);
  1675. }
  1676. private getNodeContent(node: TreeNode) {
  1677. if (node === SENTINEL) {
  1678. return '';
  1679. }
  1680. const buffer = this._buffers[node.piece.bufferIndex];
  1681. const piece = node.piece;
  1682. const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
  1683. const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
  1684. const currentContent = buffer.buffer.substring(startOffset, endOffset);
  1685. return currentContent;
  1686. }
  1687. getPieceContent(piece: Piece) {
  1688. const buffer = this._buffers[piece.bufferIndex];
  1689. const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
  1690. const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
  1691. const currentContent = buffer.buffer.substring(startOffset, endOffset);
  1692. return currentContent;
  1693. }
  1694. /**
  1695. * node node
  1696. * / \ / \
  1697. * a b <---- a b
  1698. * /
  1699. * z
  1700. */
  1701. private rbInsertRight(node: TreeNode | null, p: Piece): TreeNode {
  1702. const z = new TreeNode(p, NodeColor.Red);
  1703. z.left = SENTINEL;
  1704. z.right = SENTINEL;
  1705. z.parent = SENTINEL;
  1706. z.size_left = 0;
  1707. z.lf_left = 0;
  1708. const x = this.root;
  1709. if (x === SENTINEL) {
  1710. this.root = z;
  1711. z.color = NodeColor.Black;
  1712. } else if (node!.right === SENTINEL) {
  1713. node!.right = z;
  1714. z.parent = node!;
  1715. } else {
  1716. const nextNode = leftest(node!.right);
  1717. nextNode.left = z;
  1718. z.parent = nextNode;
  1719. }
  1720. fixInsert(this, z);
  1721. return z;
  1722. }
  1723. /**
  1724. * node node
  1725. * / \ / \
  1726. * a b ----> a b
  1727. * \
  1728. * z
  1729. */
  1730. private rbInsertLeft(node: TreeNode | null, p: Piece): TreeNode {
  1731. const z = new TreeNode(p, NodeColor.Red);
  1732. z.left = SENTINEL;
  1733. z.right = SENTINEL;
  1734. z.parent = SENTINEL;
  1735. z.size_left = 0;
  1736. z.lf_left = 0;
  1737. if (this.root === SENTINEL) {
  1738. this.root = z;
  1739. z.color = NodeColor.Black;
  1740. } else if (node!.left === SENTINEL) {
  1741. node!.left = z;
  1742. z.parent = node!;
  1743. } else {
  1744. const prevNode = righttest(node!.left); // a
  1745. prevNode.right = z;
  1746. z.parent = prevNode;
  1747. }
  1748. fixInsert(this, z);
  1749. return z;
  1750. }
  1751. private getContentOfSubTree(node: TreeNode): string {
  1752. let str = '';
  1753. this.iterate(node, node => {
  1754. str += this.getNodeContent(node);
  1755. return true;
  1756. });
  1757. return str;
  1758. }
  1759. // #endregion
  1760. }