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