diff --git a/src/extension.ts b/src/extension.ts index 99734a2..7f5191c 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -2,6 +2,7 @@ import * as vscode from 'vscode'; import { exec } from 'child_process'; import * as os from 'os'; import * as fs from 'fs'; +import * as path from 'path'; function getMacIdeaPath(): string { const commonPaths = [ @@ -27,6 +28,25 @@ function getMacIdeaPath(): string { return 'IntelliJ IDEA'; } +function getIdeaProjectPath(filePath: string): string | undefined { + let currentPath = path.dirname(filePath); + + // 优先使用离当前文件最近的 .idea 目录,避免将多项目工作区的上层目录误当成 IDEA 项目根目录 + while (true) { + if (fs.existsSync(path.join(currentPath, '.idea'))) { + return currentPath; + } + + const parentPath = path.dirname(currentPath); + if (parentPath === currentPath) { + break; + } + currentPath = parentPath; + } + + return vscode.workspace.getWorkspaceFolder(vscode.Uri.file(filePath))?.uri.fsPath; +} + function executeCommand(command: string): Promise { return new Promise((resolve, reject) => { const childProcess = exec(command, (error, stdout, stderr) => { @@ -104,7 +124,10 @@ export function activate(context: vscode.ExtensionContext) { // Using the 'open' command instead will prevent this issue command = `open -a "${ideaPath}" "${ideaUrl}"`; } else { - command = `"${ideaPath}" --line ${line} --column ${column} "${filePath}"`; + const projectPath = getIdeaProjectPath(filePath); + // IDEA 2026.2 需要在定位参数前提供项目上下文,否则可能无法识别 --line + const projectArgument = projectPath ? ` "${projectPath}"` : ''; + command = `"${ideaPath}"${projectArgument} --line ${line} --column ${column} "${filePath}"`; } console.log('Executing command:', command);