|
| 1 | +import { FlashStyle, Position, Range, TextEditor } from "@cursorless/common"; |
| 2 | +import { flatten, zip } from "lodash"; |
| 3 | +import type { RangeUpdater } from "../core/updateSelections/RangeUpdater"; |
| 4 | +import { performEditsAndUpdateRanges } from "../core/updateSelections/updateSelections"; |
| 5 | +import { ide } from "../singletons/ide.singleton"; |
| 6 | +import { Edit } from "../typings/Types"; |
| 7 | +import { Target } from "../typings/target.types"; |
| 8 | +import { flashTargets, runOnTargetsForEachEditor } from "../util/targetUtils"; |
| 9 | +import type { ActionReturnValue } from "./actions.types"; |
| 10 | + |
| 11 | +export class BreakLine { |
| 12 | + constructor(private rangeUpdater: RangeUpdater) { |
| 13 | + this.run = this.run.bind(this); |
| 14 | + } |
| 15 | + |
| 16 | + async run(targets: Target[]): Promise<ActionReturnValue> { |
| 17 | + await flashTargets(ide(), targets, FlashStyle.pendingModification0); |
| 18 | + |
| 19 | + const thatSelections = flatten( |
| 20 | + await runOnTargetsForEachEditor(targets, async (editor, targets) => { |
| 21 | + const contentRanges = targets.map(({ contentRange }) => contentRange); |
| 22 | + const edits = getEdits(editor, contentRanges); |
| 23 | + |
| 24 | + const [updatedRanges] = await performEditsAndUpdateRanges( |
| 25 | + this.rangeUpdater, |
| 26 | + ide().getEditableTextEditor(editor), |
| 27 | + edits, |
| 28 | + [contentRanges], |
| 29 | + ); |
| 30 | + |
| 31 | + return zip(targets, updatedRanges).map(([target, range]) => ({ |
| 32 | + editor: target!.editor, |
| 33 | + selection: range!.toSelection(target!.isReversed), |
| 34 | + })); |
| 35 | + }), |
| 36 | + ); |
| 37 | + |
| 38 | + return { thatSelections }; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +function getEdits(editor: TextEditor, contentRanges: Range[]): Edit[] { |
| 43 | + const { document } = editor; |
| 44 | + const edits: Edit[] = []; |
| 45 | + |
| 46 | + for (const range of contentRanges) { |
| 47 | + const position = range.start; |
| 48 | + const line = document.lineAt(position); |
| 49 | + const indentation = line.text.slice( |
| 50 | + 0, |
| 51 | + line.firstNonWhitespaceCharacterIndex, |
| 52 | + ); |
| 53 | + const characterTrailingWhitespace = line.text |
| 54 | + .slice(0, position.character) |
| 55 | + .search(/\s+$/); |
| 56 | + const replacementRange = |
| 57 | + characterTrailingWhitespace > -1 |
| 58 | + ? new Range( |
| 59 | + new Position(line.lineNumber, characterTrailingWhitespace), |
| 60 | + position, |
| 61 | + ) |
| 62 | + : position.toEmptyRange(); |
| 63 | + |
| 64 | + edits.push({ |
| 65 | + range: replacementRange, |
| 66 | + text: "\n" + indentation, |
| 67 | + isReplace: !replacementRange.isEmpty, |
| 68 | + }); |
| 69 | + } |
| 70 | + |
| 71 | + return edits; |
| 72 | +} |
0 commit comments