replaceAllCommand.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import { Range } from '../../common/core/range.js';
  6. export class ReplaceAllCommand {
  7. constructor(editorSelection, ranges, replaceStrings) {
  8. this._editorSelection = editorSelection;
  9. this._ranges = ranges;
  10. this._replaceStrings = replaceStrings;
  11. this._trackedEditorSelectionId = null;
  12. }
  13. getEditOperations(model, builder) {
  14. if (this._ranges.length > 0) {
  15. // Collect all edit operations
  16. let ops = [];
  17. for (let i = 0; i < this._ranges.length; i++) {
  18. ops.push({
  19. range: this._ranges[i],
  20. text: this._replaceStrings[i]
  21. });
  22. }
  23. // Sort them in ascending order by range starts
  24. ops.sort((o1, o2) => {
  25. return Range.compareRangesUsingStarts(o1.range, o2.range);
  26. });
  27. // Merge operations that touch each other
  28. let resultOps = [];
  29. let previousOp = ops[0];
  30. for (let i = 1; i < ops.length; i++) {
  31. if (previousOp.range.endLineNumber === ops[i].range.startLineNumber && previousOp.range.endColumn === ops[i].range.startColumn) {
  32. // These operations are one after another and can be merged
  33. previousOp.range = previousOp.range.plusRange(ops[i].range);
  34. previousOp.text = previousOp.text + ops[i].text;
  35. }
  36. else {
  37. resultOps.push(previousOp);
  38. previousOp = ops[i];
  39. }
  40. }
  41. resultOps.push(previousOp);
  42. for (const op of resultOps) {
  43. builder.addEditOperation(op.range, op.text);
  44. }
  45. }
  46. this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection);
  47. }
  48. computeCursorState(model, helper) {
  49. return helper.getTrackedSelection(this._trackedEditorSelectionId);
  50. }
  51. }