-
Notifications
You must be signed in to change notification settings - Fork 328
/
Copy pathmain.ts
466 lines (420 loc) · 13.7 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
/**
* A tagging type for string properties that are actually URIs.
*/
export type DocumentUri = string;
/**
* Position in a text document expressed as zero-based line and character offset.
* The offsets are based on a UTF-16 string representation. So a string of the form
* `a𐐀b` the character offset of the character `a` is 0, the character offset of `𐐀`
* is 1 and the character offset of b is 3 since `𐐀` is represented using two code
* units in UTF-16.
*
* Positions are line end character agnostic. So you can not specify a position that
* denotes `\r|\n` or `\n|` where `|` represents the character offset.
*/
export interface Position {
/**
* Line position in a document (zero-based).
*
* If a line number is greater than the number of lines in a document, it
* defaults back to the number of lines in the document.
* If a line number is negative, it defaults to 0.
*
* The above two properties are implementation specific.
*/
line: number;
/**
* Character offset on a line in a document (zero-based).
*
* The meaning of this offset is determined by the negotiated
* `PositionEncodingKind`.
*
* If the character value is greater than the line length it defaults back
* to the line length. This property is implementation specific.
*/
character: number;
}
/**
* A range in a text document expressed as (zero-based) start and end positions.
*
* If you want to specify a range that contains a line including the line ending
* character(s) then use an end position denoting the start of the next line.
* For example:
* ```ts
* {
* start: { line: 5, character: 23 }
* end : { line 6, character : 0 }
* }
* ```
*/
export interface Range {
/**
* The range's start position.
*/
start: Position;
/**
* The range's end position.
*/
end: Position;
}
/**
* A text edit applicable to a text document.
*/
export interface TextEdit {
/**
* The range of the text document to be manipulated. To insert
* text into a document create a range where start === end.
*/
range: Range;
/**
* The string to be inserted. For delete operations use an
* empty string.
*/
newText: string;
}
/**
* An event describing a change to a text document. If range and rangeLength are omitted
* the new text is considered to be the full content of the document.
*/
export type TextDocumentContentChangeEvent = {
/**
* The range of the document that changed.
*/
range: Range;
/**
* The optional length of the range that got replaced.
*
* @deprecated use range instead.
*/
rangeLength?: number;
/**
* The new text for the provided range.
*/
text: string;
} | {
/**
* The new text of the whole document.
*/
text: string;
};
/**
* A simple text document. Not to be implemented. The document keeps the content
* as string.
*/
export interface TextDocument {
/**
* The associated URI for this document. Most documents have the __file__-scheme, indicating that they
* represent files on disk. However, some documents may have other schemes indicating that they are not
* available on disk.
*
* @readonly
*/
readonly uri: DocumentUri;
/**
* The identifier of the language associated with this document.
*
* @readonly
*/
readonly languageId: string;
/**
* The version number of this document (it will increase after each
* change, including undo/redo).
*
* @readonly
*/
readonly version: number;
/**
* Get the text of this document. A substring can be retrieved by
* providing a range.
*
* @param range (optional) An range within the document to return.
* If no range is passed, the full content is returned.
* Invalid range positions are adjusted as described in {@link Position.line}
* and {@link Position.character}.
* If the start range position is greater than the end range position,
* then the effect of getText is as if the two positions were swapped.
* @return The text of this document or a substring of the text if a
* range is provided.
*/
getText(range?: Range): string;
/**
* Converts a zero-based offset to a position.
*
* @param offset A zero-based offset.
* @return A valid {@link Position position}.
* @example The text document "ab\ncd" produces:
* * position { line: 0, character: 0 } for `offset` 0.
* * position { line: 0, character: 1 } for `offset` 1.
* * position { line: 0, character: 2 } for `offset` 2.
* * position { line: 1, character: 0 } for `offset` 3.
* * position { line: 1, character: 1 } for `offset` 4.
*/
positionAt(offset: number): Position;
/**
* Converts the position to a zero-based offset.
* Invalid positions are adjusted as described in {@link Position.line}
* and {@link Position.character}.
*
* @param position A position.
* @return A valid zero-based offset.
*/
offsetAt(position: Position): number;
/**
* The number of lines in this document.
*
* @readonly
*/
readonly lineCount: number;
}
class FullTextDocument implements TextDocument {
private _uri: DocumentUri;
private _languageId: string;
private _version: number;
private _content: string;
private _lineOffsets: number[] | undefined;
public constructor(uri: DocumentUri, languageId: string, version: number, content: string) {
this._uri = uri;
this._languageId = languageId;
this._version = version;
this._content = content;
this._lineOffsets = undefined;
}
public get uri(): string {
return this._uri;
}
public get languageId(): string {
return this._languageId;
}
public get version(): number {
return this._version;
}
public getText(range?: Range): string {
if (range) {
const start = this.offsetAt(range.start);
const end = this.offsetAt(range.end);
return this._content.substring(start, end);
}
return this._content;
}
public update(changes: TextDocumentContentChangeEvent[], version: number): void {
for (let change of changes) {
if (FullTextDocument.isIncremental(change)) {
// makes sure start is before end
const range = getWellformedRange(change.range);
// update content
const startOffset = this.offsetAt(range.start);
const endOffset = this.offsetAt(range.end);
this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
// update the offsets
const startLine = Math.max(range.start.line, 0);
const endLine = Math.max(range.end.line, 0);
let lineOffsets = this._lineOffsets!;
const addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
if (endLine - startLine === addedLineOffsets.length) {
for (let i = 0, len = addedLineOffsets.length; i < len; i++) {
lineOffsets[i + startLine + 1] = addedLineOffsets[i];
}
} else {
if (addedLineOffsets.length < 10000) {
lineOffsets.splice(startLine + 1, endLine - startLine, ...addedLineOffsets);
} else { // avoid too many arguments for splice
this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
}
}
const diff = change.text.length - (endOffset - startOffset);
if (diff !== 0) {
for (let i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {
lineOffsets[i] = lineOffsets[i] + diff;
}
}
} else if (FullTextDocument.isFull(change)) {
this._content = change.text;
this._lineOffsets = undefined;
} else {
throw new Error('Unknown change event received');
}
}
this._version = version;
}
private getLineOffsets(): number[] {
if (this._lineOffsets === undefined) {
this._lineOffsets = computeLineOffsets(this._content, true);
}
return this._lineOffsets;
}
public positionAt(offset: number): Position {
offset = Math.max(Math.min(offset, this._content.length), 0);
let lineOffsets = this.getLineOffsets();
let low = 0, high = lineOffsets.length;
if (high === 0) {
return { line: 0, character: offset };
}
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (lineOffsets[mid] > offset) {
high = mid;
} else {
low = mid + 1;
}
}
// low is the least x for which the line offset is larger than the current offset
// or array.length if no line offset is larger than the current offset
let line = low - 1;
return { line, character: offset - lineOffsets[line] };
}
public offsetAt(position: Position) {
let lineOffsets = this.getLineOffsets();
if (position.line >= lineOffsets.length) {
return this._content.length;
} else if (position.line < 0) {
return 0;
}
let lineOffset = lineOffsets[position.line];
let nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
}
public get lineCount() {
return this.getLineOffsets().length;
}
private static isIncremental(event: TextDocumentContentChangeEvent): event is { range: Range; rangeLength?: number; text: string } {
let candidate: { range: Range; rangeLength?: number; text: string } = event as any;
return candidate !== undefined && candidate !== null &&
typeof candidate.text === 'string' && candidate.range !== undefined &&
(candidate.rangeLength === undefined || typeof candidate.rangeLength === 'number');
}
private static isFull(event: TextDocumentContentChangeEvent): event is { text: string } {
let candidate: { range?: Range; rangeLength?: number; text: string } = event as any;
return candidate !== undefined && candidate !== null &&
typeof candidate.text === 'string' && candidate.range === undefined && candidate.rangeLength === undefined;
}
}
export namespace TextDocument {
/**
* Creates a new text document.
*
* @param uri The document's uri.
* @param languageId The document's language Id.
* @param version The document's initial version number.
* @param content The document's content.
*/
export function create(uri: DocumentUri, languageId: string, version: number, content: string): TextDocument {
return new FullTextDocument(uri, languageId, version, content);
}
/**
* Updates a TextDocument by modifying its content.
*
* @param document the document to update. Only documents created by TextDocument.create are valid inputs.
* @param changes the changes to apply to the document.
* @param version the changes version for the document.
* @returns The updated TextDocument. Note: That's the same document instance passed in as first parameter.
*
*/
export function update(document: TextDocument, changes: TextDocumentContentChangeEvent[], version: number): TextDocument {
if (document instanceof FullTextDocument) {
document.update(changes, version);
return document;
} else {
throw new Error('TextDocument.update: document must be created by TextDocument.create');
}
}
export function applyEdits(document: TextDocument, edits: TextEdit[]): string {
let text = document.getText();
let sortedEdits = mergeSort(edits.map(getWellformedEdit), (a, b) => {
let diff = a.range.start.line - b.range.start.line;
if (diff === 0) {
return a.range.start.character - b.range.start.character;
}
return diff;
});
let lastModifiedOffset = 0;
const spans = [];
for (const e of sortedEdits) {
let startOffset = document.offsetAt(e.range.start);
if (startOffset < lastModifiedOffset) {
throw new Error('Overlapping edit');
} else if (startOffset > lastModifiedOffset) {
spans.push(text.substring(lastModifiedOffset, startOffset));
}
if (e.newText.length) {
spans.push(e.newText);
}
lastModifiedOffset = document.offsetAt(e.range.end);
}
spans.push(text.substr(lastModifiedOffset));
return spans.join('');
}
}
function mergeSort<T>(data: T[], compare: (a: T, b: T) => number): T[] {
if (data.length <= 1) {
// sorted
return data;
}
const p = (data.length / 2) | 0;
const left = data.slice(0, p);
const right = data.slice(p);
mergeSort(left, compare);
mergeSort(right, compare);
let leftIdx = 0;
let rightIdx = 0;
let i = 0;
while (leftIdx < left.length && rightIdx < right.length) {
let ret = compare(left[leftIdx], right[rightIdx]);
if (ret <= 0) {
// smaller_equal -> take left to preserve order
data[i++] = left[leftIdx++];
} else {
// greater -> take right
data[i++] = right[rightIdx++];
}
}
while (leftIdx < left.length) {
data[i++] = left[leftIdx++];
}
while (rightIdx < right.length) {
data[i++] = right[rightIdx++];
}
return data;
}
const enum CharCode {
/**
* The `\n` character.
*/
LineFeed = 10,
/**
* The `\r` character.
*/
CarriageReturn = 13,
}
function computeLineOffsets(text: string, isAtLineStart: boolean, textOffset = 0): number[] {
const result: number[] = isAtLineStart ? [textOffset] : [];
for (let i = 0; i < text.length; i++) {
let ch = text.charCodeAt(i);
if (ch === CharCode.CarriageReturn || ch === CharCode.LineFeed) {
if (ch === CharCode.CarriageReturn && i + 1 < text.length && text.charCodeAt(i + 1) === CharCode.LineFeed) {
i++;
}
result.push(textOffset + i + 1);
}
}
return result;
}
function getWellformedRange(range: Range): Range {
const start = range.start;
const end = range.end;
if (start.line > end.line || (start.line === end.line && start.character > end.character)) {
return { start: end, end: start };
}
return range;
}
function getWellformedEdit(textEdit: TextEdit): TextEdit {
const range = getWellformedRange(textEdit.range);
if (range !== textEdit.range) {
return { newText: textEdit.newText, range };
}
return textEdit;
}