| 1 | import * as vscode from "vscode"; |
| 2 | |
| 3 | import { VerticalDiffManager } from "../diff/vertical/manager"; |
| 4 | import { getRangeInFileWithContents } from "../util/addCode"; |
| 5 | import { VsCodeWebviewProtocol } from "../webviewProtocol"; |
| 6 | |
| 7 | import EditDecorationManager from "./EditDecorationManager"; |
| 8 | import { QuickEditShowParams } from "./QuickEditQuickPick"; |
| 9 | |
| 10 | export async function addCurrentSelectionToEdit({ |
| 11 | webviewProtocol, |
| 12 | verticalDiffManager, |
| 13 | args, |
| 14 | editDecorationManager, |
| 15 | }: { |
| 16 | webviewProtocol: VsCodeWebviewProtocol; |
| 17 | verticalDiffManager: VerticalDiffManager; |
| 18 | args: QuickEditShowParams | undefined; |
| 19 | editDecorationManager: EditDecorationManager; |
| 20 | }) { |
| 21 | const editor = vscode.window.activeTextEditor; |
| 22 | |
| 23 | if (!editor) { |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | const existingDiff = verticalDiffManager.getHandlerForFile( |
| 28 | editor.document.fileName, |
| 29 | ); |
| 30 | |
| 31 | // If there's a diff currently being applied, then we just toggle focus back to the input |
| 32 | if (existingDiff) { |
| 33 | webviewProtocol?.request("focusContinueInput", undefined); |
| 34 | return; |
| 35 | } |
| 36 | |
| 37 | const startFromCharZero = editor.selection.start.with(undefined, 0); |
| 38 | const document = editor.document; |
| 39 | let lastLine, lastChar; |
| 40 | // If the user selected onto a trailing line but didn't actually include any characters in it |
| 41 | // they don't want to include that line, so trim it off. |
| 42 | if (editor.selection.end.character === 0) { |
| 43 | // This is to prevent the rare case that the previous line gets selected when user |
| 44 | // is selecting nothing and the cursor is at the beginning of the line |
| 45 | if (editor.selection.end.line === editor.selection.start.line) { |
| 46 | lastLine = editor.selection.start.line; |
| 47 | } else { |
| 48 | lastLine = editor.selection.end.line - 1; |
| 49 | } |
| 50 | } else { |
| 51 | lastLine = editor.selection.end.line; |
| 52 | } |
| 53 | lastChar = document.lineAt(lastLine).range.end.character; |
| 54 | const endAtCharLast = new vscode.Position(lastLine, lastChar); |
| 55 | const range = |
| 56 | args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast); |
| 57 | |
| 58 | editDecorationManager.clear(); |
| 59 | editDecorationManager.addDecorations(editor, [range]); |
| 60 | |
| 61 | const rangeInFileWithContents = getRangeInFileWithContents(true, range); |
| 62 | |
| 63 | if (rangeInFileWithContents) { |
| 64 | webviewProtocol?.request("setCodeToEdit", rangeInFileWithContents); |
| 65 | |
| 66 | // Un-select the current selection |
| 67 | editor.selection = new vscode.Selection( |
| 68 | editor.selection.anchor, |
| 69 | editor.selection.anchor, |
| 70 | ); |
| 71 | } |
| 72 | } |