Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/editor/contrib/find/browser/replaceAllCommand.ts
3296 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { Range } from '../../../common/core/range.js';
7
import { Selection } from '../../../common/core/selection.js';
8
import { ICommand, ICursorStateComputerData, IEditOperationBuilder } from '../../../common/editorCommon.js';
9
import { ITextModel } from '../../../common/model.js';
10
11
interface IEditOperation {
12
range: Range;
13
text: string;
14
}
15
16
export class ReplaceAllCommand implements ICommand {
17
18
private readonly _editorSelection: Selection;
19
private _trackedEditorSelectionId: string | null;
20
private readonly _ranges: Range[];
21
private readonly _replaceStrings: string[];
22
23
constructor(editorSelection: Selection, ranges: Range[], replaceStrings: string[]) {
24
this._editorSelection = editorSelection;
25
this._ranges = ranges;
26
this._replaceStrings = replaceStrings;
27
this._trackedEditorSelectionId = null;
28
}
29
30
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
31
if (this._ranges.length > 0) {
32
// Collect all edit operations
33
const ops: IEditOperation[] = [];
34
for (let i = 0; i < this._ranges.length; i++) {
35
ops.push({
36
range: this._ranges[i],
37
text: this._replaceStrings[i]
38
});
39
}
40
41
// Sort them in ascending order by range starts
42
ops.sort((o1, o2) => {
43
return Range.compareRangesUsingStarts(o1.range, o2.range);
44
});
45
46
// Merge operations that touch each other
47
const resultOps: IEditOperation[] = [];
48
let previousOp = ops[0];
49
for (let i = 1; i < ops.length; i++) {
50
if (previousOp.range.endLineNumber === ops[i].range.startLineNumber && previousOp.range.endColumn === ops[i].range.startColumn) {
51
// These operations are one after another and can be merged
52
previousOp.range = previousOp.range.plusRange(ops[i].range);
53
previousOp.text = previousOp.text + ops[i].text;
54
} else {
55
resultOps.push(previousOp);
56
previousOp = ops[i];
57
}
58
}
59
resultOps.push(previousOp);
60
61
for (const op of resultOps) {
62
builder.addEditOperation(op.range, op.text);
63
}
64
}
65
66
this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection);
67
}
68
69
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
70
return helper.getTrackedSelection(this._trackedEditorSelectionId!);
71
}
72
}
73
74