Skip to content

Commit 8f303bb

Browse files
committed
feat: use selection
fix #10
1 parent 98d69f0 commit 8f303bb

File tree

1 file changed

+28
-14
lines changed

1 file changed

+28
-14
lines changed

packages/utils-ai-vscode/src/commands/correct.ts

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,38 +6,52 @@ export function correctCommand(context: vscode.ExtensionContext) {
66
const secrets = context.secrets
77

88
return async () => {
9+
const accessKey = await getOpenAIKey(secrets)
10+
11+
if (!accessKey) {
12+
vscode.window.showErrorMessage('No key provided. Please provide a key using the "Add OpenAI Key" command.')
13+
return
14+
}
15+
916
const time = Date.now()
1017
const editor = vscode.window.activeTextEditor
1118

1219
if (editor) {
13-
const accessKey = await getOpenAIKey(secrets)
14-
15-
if (!accessKey) {
16-
vscode.window.showErrorMessage('No key provided. Please provide a key using the "Add OpenAI Key" command.')
17-
return
18-
}
19-
2020
const prompt = getPrompt('spell-checker-md', 'en')
2121
const filename = editor.document.fileName
22-
const text = editor.document.getText()
22+
23+
const hasSelection = !editor.selection.isEmpty
24+
const selection = editor.selection
25+
26+
// First, use the selection then the whole document
27+
let text: string
28+
if (hasSelection)
29+
text = editor.document.getText(selection)
30+
else
31+
text = editor.document.getText()
2332

2433
try {
25-
// start a loading notification
34+
const title = hasSelection ? `Correcting selection in ${filename}. Please wait...` : `Correcting text in ${filename}. Please wait...`
2635
await vscode.window.withProgress({
2736
location: vscode.ProgressLocation.Notification,
28-
title: `Correcting ${filename}. Please wait...`,
37+
title,
2938
cancellable: false,
3039
}, async () => {
3140
const correctedText = await correct(text, prompt.message, { ai: { accessKey } })
3241

33-
// replace the text with the corrected text
3442
editor.edit((editBuilder) => {
35-
editBuilder.replace(new vscode.Range(0, 0, text.length, 0), correctedText)
43+
const range: vscode.Range = hasSelection ? selection : new vscode.Range(0, 0, text.length, 0)
44+
45+
editBuilder.delete(range)
46+
editBuilder.insert(range.start, correctedText)
3647
})
3748

49+
// Save the document
50+
await editor.document.save()
51+
3852
const duration = Date.now() - time
39-
// show a success notification
40-
vscode.window.showInformationMessage(`Corrected text in ${filename}`, {
53+
const message = hasSelection ? `Selection corrected in ${filename}` : `Text corrected in ${filename}`
54+
vscode.window.showInformationMessage(message, {
4155
detail: `Done in ${duration}ms.`,
4256
})
4357
})

0 commit comments

Comments
 (0)