Files
squirrelVsis/src/providers/documentFormattingProvider.ts

50 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-09-17 10:54:25 +08:00
import * as vscode from 'vscode';
2025-09-17 11:28:54 +08:00
import { beautifyCode, isSquirrelCode } from '../utils/beautifyHelper';
2025-09-17 10:54:25 +08:00
2025-09-17 11:28:54 +08:00
/**
* - 使 js-beautify.js
*/
2025-09-17 10:54:25 +08:00
export class DocumentFormattingProvider implements vscode.DocumentFormattingEditProvider {
2025-09-17 11:28:54 +08:00
/**
*
*/
2025-09-17 10:54:25 +08:00
async provideDocumentFormattingEdits(
document: vscode.TextDocument,
options: vscode.FormattingOptions,
token: vscode.CancellationToken
): Promise<vscode.TextEdit[]> {
const edits: vscode.TextEdit[] = [];
2025-09-17 11:28:54 +08:00
try {
// 获取文档全文
const fullText = document.getText();
2025-09-17 10:54:25 +08:00
2025-09-17 11:28:54 +08:00
// 检查是否是 Squirrel 代码
if (!isSquirrelCode(fullText)) {
return edits; // 如果不是 Squirrel 代码,不应用格式化
2025-09-17 10:54:25 +08:00
}
2025-09-17 11:28:54 +08:00
// 使用 js-beautify 格式化代码
const formattedText = beautifyCode(fullText, options);
2025-09-17 10:54:25 +08:00
2025-09-17 11:28:54 +08:00
// 如果格式化后的代码与原代码相同,不需要修改
if (formattedText === fullText) {
return edits;
2025-09-17 10:54:25 +08:00
}
2025-09-17 11:28:54 +08:00
// 创建编辑操作,替换整个文档
const fullRange = new vscode.Range(
document.positionAt(0),
document.positionAt(fullText.length)
);
2025-09-17 10:54:25 +08:00
2025-09-17 11:28:54 +08:00
edits.push(vscode.TextEdit.replace(fullRange, formattedText));
2025-09-17 10:54:25 +08:00
2025-09-17 11:28:54 +08:00
} catch (error) {
console.error('文档格式化失败:', error);
// 如果格式化失败,返回空编辑数组,保持原代码不变
2025-09-17 10:54:25 +08:00
}
2025-09-17 11:28:54 +08:00
return edits;
2025-09-17 10:54:25 +08:00
}
}