Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,35 @@ The extension provides several configuration options to customize your SageMath

You can configure these settings in your VS Code settings (File > Preferences > Settings) by searching for "SageMath Enhanced".

## Troubleshooting

### SageMath Not Found Error

If you see an error message that "SageMath is not installed or not found in PATH" when trying to run .sage files:

1. **Install SageMath**: If you haven't installed SageMath yet, visit the [official installation guide](https://doc.sagemath.org/html/en/installation/).

2. **Configure Path**: If SageMath is installed but not in your system PATH:
- Open VS Code settings (File > Preferences > Settings)
- Search for "SageMath Enhanced"
- Set `sagemathEnhanced.interpreterPath` to the full path of your SageMath installation
- Common paths:
- Linux/macOS: `/usr/local/bin/sage` or `/opt/sage/sage`
- Windows: `C:\SageMath\sage.exe`

3. **Test Installation**: You can test if SageMath is properly configured by opening a terminal and running:
```bash
sage --version
```

### Language Server Issues

If you experience problems with code completion, hover documentation, or diagnostics:

1. **Restart Language Server**: Use Command Palette (`Ctrl+Shift+P`) and run "Restart SageMath Language Server"
2. **Check Extension Status**: Look for any error messages in the VS Code Output panel (View > Output, select "SageMath Enhanced")
3. **Verify File Association**: Ensure your file has the `.sage` extension and the language mode is set to "SageMath"

## Requirements

- [Visual Studio Code](https://code.visualstudio.com/) version 1.76.0 or higher.
Expand Down
29 changes: 29 additions & 0 deletions README.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,35 @@ https://github.com/n-WN/sagemath-vscode-enhanced/assets/30841158/2a8d5cea-8c21-4

- **集成终端**:您的SageMath脚本输出以及任何错误或警告将显示在VS Code的集成终端中。这允许轻松调试和与您的代码交互。

## 故障排除

### SageMath未找到错误

如果在尝试运行.sage文件时看到"SageMath未安装或在PATH中未找到"的错误消息:

1. **安装SageMath**:如果您尚未安装SageMath,请访问[官方安装指南](https://doc.sagemath.org/html/en/installation/)。

2. **配置路径**:如果已安装SageMath但不在系统PATH中:
- 打开VS Code设置(文件 > 首选项 > 设置)
- 搜索"SageMath Enhanced"
- 将`sagemathEnhanced.interpreterPath`设置为SageMath安装的完整路径
- 常见路径:
- Linux/macOS: `/usr/local/bin/sage` 或 `/opt/sage/sage`
- Windows: `C:\SageMath\sage.exe`

3. **测试安装**:您可以通过打开终端并运行以下命令来测试SageMath是否正确配置:
```bash
sage --version
```

### 语言服务器问题

如果您在代码补全、悬停文档或诊断方面遇到问题:

1. **重启语言服务器**:使用命令面板(`Ctrl+Shift+P`)并运行"重启SageMath语言服务器"
2. **检查扩展状态**:在VS Code输出面板中查看任何错误消息(查看 > 输出,选择"SageMath Enhanced")
3. **验证文件关联**:确保您的文件具有`.sage`扩展名,并且语言模式设置为"SageMath"

## 要求

- [Visual Studio Code](https://code.visualstudio.com/) 版本 1.76.0 或更高。
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@
"enum": ["off", "error", "warn", "info", "debug"],
"default": "info",
"description": "Language server log level"
},
"sagemathEnhanced.dontShowSageWarning": {
"type": "boolean",
"default": false,
"description": "Don't show the SageMath installation warning on extension activation"
}
}
},
Expand Down
91 changes: 90 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { exec } from 'child_process';
import { promisify } from 'util';

import {
LanguageClient,
Expand All @@ -9,11 +11,52 @@ import {
TransportKind
} from 'vscode-languageclient/node';

const execAsync = promisify(exec);

let client: LanguageClient;

/**
* Check if SageMath is available on the system
* @param sagePath Path to the SageMath interpreter
* @returns Promise<boolean> indicating if SageMath is available
*/
async function checkSageMathAvailability(sagePath: string): Promise<boolean> {
try {
// Try to run sage --version to check if it's available
const command = process.platform === 'win32' ? `where ${sagePath}` : `which ${sagePath}`;
await execAsync(command);
return true;
} catch (error) {
try {
// Fallback: try to run sage directly with --version
await execAsync(`${sagePath} --version`);
return true;
} catch (secondError) {
return false;
}
}
}

/**
* Show SageMath installation guidance to the user
*/
function showSageMathInstallationGuidance(): void {
const installMessage = 'SageMath is not installed or not found in PATH. Please install SageMath to run .sage files.';
const installButton = 'Installation Guide';
const configButton = 'Configure Path';

vscode.window.showErrorMessage(installMessage, installButton, configButton).then(selection => {
if (selection === installButton) {
vscode.env.openExternal(vscode.Uri.parse('https://doc.sagemath.org/html/en/installation/'));
} else if (selection === configButton) {
vscode.commands.executeCommand('workbench.action.openSettings', 'sagemathEnhanced.interpreterPath');
}
});
}

export function activate(context: vscode.ExtensionContext) {
// Register the run command first to ensure it's available even if language server fails
let runDisposable = vscode.commands.registerCommand('runsagemathfile.run', () => {
let runDisposable = vscode.commands.registerCommand('runsagemathfile.run', async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
console.log('No editor is active');
Expand All @@ -28,6 +71,13 @@ export function activate(context: vscode.ExtensionContext) {

const sagePath = vscode.workspace.getConfiguration().get('sagemathEnhanced.interpreterPath') as string;

// Check if SageMath is available before trying to run
const isSageAvailable = await checkSageMathAvailability(sagePath);
if (!isSageAvailable) {
showSageMathInstallationGuidance();
return;
}

const filePath = document.fileName;
const fileDir = path.dirname(filePath);
const fileName = path.basename(filePath);
Expand Down Expand Up @@ -83,13 +133,52 @@ export function activate(context: vscode.ExtensionContext) {

context.subscriptions.push(runDisposable, restartDisposable);

// Check SageMath availability on activation and show guidance if needed
checkSageMathAvailabilityOnActivation();

// Start the Language Server asynchronously to avoid blocking command registration
startLanguageServer(context).catch(error => {
console.error('Failed to start SageMath Language Server:', error);
vscode.window.showWarningMessage('SageMath Language Server failed to start. Some features may not be available.');
});
}

/**
* Check SageMath availability when the extension activates
* Show a one-time informational message if SageMath is not available
*/
async function checkSageMathAvailabilityOnActivation(): Promise<void> {
try {
const sagePath = vscode.workspace.getConfiguration().get('sagemathEnhanced.interpreterPath') as string;
const isSageAvailable = await checkSageMathAvailability(sagePath);

if (!isSageAvailable) {
// Only show this message if the user hasn't seen it before
const dontShowAgainKey = 'sagemathEnhanced.dontShowSageWarning';
const dontShowAgain = vscode.workspace.getConfiguration().get(dontShowAgainKey) as boolean;

if (!dontShowAgain) {
const message = 'SageMath is not detected on your system. You can still use language features, but running .sage files requires SageMath installation.';
const installButton = 'Install SageMath';
const configButton = 'Configure Path';
const dontShowButton = "Don't Show Again";

vscode.window.showInformationMessage(message, installButton, configButton, dontShowButton).then(selection => {
if (selection === installButton) {
vscode.env.openExternal(vscode.Uri.parse('https://doc.sagemath.org/html/en/installation/'));
} else if (selection === configButton) {
vscode.commands.executeCommand('workbench.action.openSettings', 'sagemathEnhanced.interpreterPath');
} else if (selection === dontShowButton) {
vscode.workspace.getConfiguration().update(dontShowAgainKey, true, vscode.ConfigurationTarget.Global);
}
});
}
}
} catch (error) {
console.error('Error checking SageMath availability on activation:', error);
}
}

async function startLanguageServer(context: vscode.ExtensionContext): Promise<void> {
try {
// The server is implemented in the server directory
Expand Down