@@ -8,6 +8,7 @@ import { SqlCodeLensProvider } from "./SqlCodeLensProvider";
88import { ConfigurationService } from "./configurationService" ;
99import { LanguageService } from "./LanguageService" ;
1010import path from "path" ;
11+ import parse from "./utils/parse" ;
1112
1213export class CommandManager {
1314 constructor (
@@ -19,6 +20,7 @@ export class CommandManager {
1920 public async initializeCommands ( ) : Promise < void > {
2021 try {
2122 this . registerApiKeyCommands ( ) ;
23+ this . registerContextMenuCommands ( ) ;
2224 } catch ( error ) {
2325 ErrorHandler . handle ( "initialize.commands.failed" , error ) ;
2426 }
@@ -32,6 +34,55 @@ export class CommandManager {
3234 this . context . subscriptions . push ( configFileDefaultDisposable ) ;
3335 }
3436
37+ private registerContextMenuCommands ( ) : void {
38+ const contextMenuOptimizeDisposable = vscode . commands . registerCommand (
39+ "pawsql.contextMenu.optimizeWithSelectedWorkspace" ,
40+ ( ) => this . handleContextMenuOptimize ( )
41+ ) ;
42+ this . context . subscriptions . push ( contextMenuOptimizeDisposable ) ;
43+ }
44+
45+ public async handleContextMenuOptimize ( ) : Promise < void > {
46+ const editor = vscode . window . activeTextEditor ;
47+ if ( ! editor || editor . document . languageId !== "sql" ) {
48+ return ;
49+ }
50+
51+ const cursorPosition = editor . selection . active ;
52+ const document = editor . document ;
53+ const text = document . getText ( ) ;
54+ const queries = await parse ( text ) ;
55+
56+ let closestQuery : { range : vscode . Range ; text : string } | null = null ;
57+ let minDistance = Number . MAX_VALUE ;
58+
59+ for ( const query of queries ) {
60+ const queryIndex = text . indexOf ( query ) ;
61+ if ( queryIndex === - 1 ) continue ;
62+
63+ const startPos = document . positionAt ( queryIndex ) ;
64+ const endPos = document . positionAt ( queryIndex + query . length ) ;
65+ const range = new vscode . Range ( startPos , endPos ) ;
66+
67+ const distance = Math . min (
68+ Math . abs ( cursorPosition . line - startPos . line ) ,
69+ Math . abs ( cursorPosition . line - endPos . line )
70+ ) ;
71+
72+ if ( distance < minDistance ) {
73+ minDistance = distance ;
74+ closestQuery = { range, text : query } ;
75+ }
76+ }
77+
78+ if ( closestQuery ) {
79+ await this . extension . handleWorkspaceSelectionWithRangeQuery (
80+ closestQuery . text ,
81+ closestQuery . range
82+ ) ;
83+ }
84+ }
85+
3586 public async handleFileDefaultWorkspaceSelection ( ) : Promise < void > {
3687 const apiKey = await ConfigurationService . getApiKey ( ) ;
3788
0 commit comments