@@ -6,38 +6,52 @@ export function correctCommand(context: vscode.ExtensionContext) {
6
6
const secrets = context . secrets
7
7
8
8
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
+
9
16
const time = Date . now ( )
10
17
const editor = vscode . window . activeTextEditor
11
18
12
19
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
-
20
20
const prompt = getPrompt ( 'spell-checker-md' , 'en' )
21
21
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 ( )
23
32
24
33
try {
25
- // start a loading notification
34
+ const title = hasSelection ? `Correcting selection in ${ filename } . Please wait...` : `Correcting text in ${ filename } . Please wait...`
26
35
await vscode . window . withProgress ( {
27
36
location : vscode . ProgressLocation . Notification ,
28
- title : `Correcting ${ filename } . Please wait...` ,
37
+ title,
29
38
cancellable : false ,
30
39
} , async ( ) => {
31
40
const correctedText = await correct ( text , prompt . message , { ai : { accessKey } } )
32
41
33
- // replace the text with the corrected text
34
42
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 )
36
47
} )
37
48
49
+ // Save the document
50
+ await editor . document . save ( )
51
+
38
52
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 , {
41
55
detail : `Done in ${ duration } ms.` ,
42
56
} )
43
57
} )
0 commit comments