|
| 1 | +import { FlashStyle, 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 | +import { range as iterRange, map, pairwise } from "itertools"; |
| 11 | + |
| 12 | +export default class JoinLines { |
| 13 | + constructor(private rangeUpdater: RangeUpdater) { |
| 14 | + this.run = this.run.bind(this); |
| 15 | + } |
| 16 | + |
| 17 | + async run(targets: Target[]): Promise<ActionReturnValue> { |
| 18 | + await flashTargets(ide(), targets, FlashStyle.pendingModification0); |
| 19 | + |
| 20 | + const thatSelections = flatten( |
| 21 | + await runOnTargetsForEachEditor(targets, async (editor, targets) => { |
| 22 | + const contentRanges = targets.map(({ contentRange }) => contentRange); |
| 23 | + const edits = getEdits(editor, contentRanges); |
| 24 | + |
| 25 | + const [updatedRanges] = await performEditsAndUpdateRanges( |
| 26 | + this.rangeUpdater, |
| 27 | + ide().getEditableTextEditor(editor), |
| 28 | + edits, |
| 29 | + [contentRanges], |
| 30 | + ); |
| 31 | + |
| 32 | + return zip(targets, updatedRanges).map(([target, range]) => ({ |
| 33 | + editor: target!.editor, |
| 34 | + selection: range!.toSelection(target!.isReversed), |
| 35 | + })); |
| 36 | + }), |
| 37 | + ); |
| 38 | + |
| 39 | + return { thatSelections }; |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +function getEdits(editor: TextEditor, contentRanges: Range[]): Edit[] { |
| 44 | + const { document } = editor; |
| 45 | + const edits: Edit[] = []; |
| 46 | + |
| 47 | + for (const range of contentRanges) { |
| 48 | + const startLine = range.start.line; |
| 49 | + const endLine = range.isSingleLine ? startLine + 1 : range.end.line; |
| 50 | + |
| 51 | + const lineIter = map(iterRange(startLine, endLine + 1), (i) => |
| 52 | + document.lineAt(i), |
| 53 | + ); |
| 54 | + for (const [line1, line2] of pairwise(lineIter)) { |
| 55 | + edits.push({ |
| 56 | + range: new Range( |
| 57 | + line1.range.end.line, |
| 58 | + line1.lastNonWhitespaceCharacterIndex, |
| 59 | + line2.range.start.line, |
| 60 | + line2.firstNonWhitespaceCharacterIndex, |
| 61 | + ), |
| 62 | + text: line2.isEmptyOrWhitespace ? "" : " ", |
| 63 | + isReplace: true, |
| 64 | + }); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return edits; |
| 69 | +} |
0 commit comments