1.0.1 代码格式化移植新版
This commit is contained in:
@@ -1,100 +1,50 @@
|
||||
import * as vscode from 'vscode';
|
||||
import { beautifyCode, isSquirrelCode } from '../utils/beautifyHelper';
|
||||
|
||||
// 文档格式化提供者类
|
||||
/**
|
||||
* 文档格式化提供者类 - 使用 js-beautify.js
|
||||
*/
|
||||
export class DocumentFormattingProvider implements vscode.DocumentFormattingEditProvider {
|
||||
// 提供整个文档的代码格式化功能
|
||||
/**
|
||||
* 提供整个文档的代码格式化功能
|
||||
*/
|
||||
async provideDocumentFormattingEdits(
|
||||
document: vscode.TextDocument,
|
||||
options: vscode.FormattingOptions,
|
||||
token: vscode.CancellationToken
|
||||
): Promise<vscode.TextEdit[]> {
|
||||
const edits: vscode.TextEdit[] = [];
|
||||
const lines: string[] = [];
|
||||
|
||||
// 逐行处理文档内容
|
||||
for (let i = 0; i < document.lineCount; i++) {
|
||||
const line = document.lineAt(i);
|
||||
lines.push(line.text);
|
||||
try {
|
||||
// 获取文档全文
|
||||
const fullText = document.getText();
|
||||
|
||||
// 检查是否是 Squirrel 代码
|
||||
if (!isSquirrelCode(fullText)) {
|
||||
return edits; // 如果不是 Squirrel 代码,不应用格式化
|
||||
}
|
||||
|
||||
// 使用 js-beautify 格式化代码
|
||||
const formattedText = beautifyCode(fullText, options);
|
||||
|
||||
// 如果格式化后的代码与原代码相同,不需要修改
|
||||
if (formattedText === fullText) {
|
||||
return edits;
|
||||
}
|
||||
|
||||
// 创建编辑操作,替换整个文档
|
||||
const fullRange = new vscode.Range(
|
||||
document.positionAt(0),
|
||||
document.positionAt(fullText.length)
|
||||
);
|
||||
|
||||
edits.push(vscode.TextEdit.replace(fullRange, formattedText));
|
||||
|
||||
} catch (error) {
|
||||
console.error('文档格式化失败:', error);
|
||||
// 如果格式化失败,返回空编辑数组,保持原代码不变
|
||||
}
|
||||
|
||||
// 格式化文档
|
||||
const formattedLines = this.formatDocument(lines, options);
|
||||
|
||||
// 创建编辑操作
|
||||
const fullRange = new vscode.Range(
|
||||
document.positionAt(0),
|
||||
document.positionAt(document.getText().length)
|
||||
);
|
||||
|
||||
edits.push(vscode.TextEdit.replace(fullRange, formattedLines.join('\n')));
|
||||
|
||||
return edits;
|
||||
}
|
||||
|
||||
// 格式化文档
|
||||
private formatDocument(lines: string[], options: vscode.FormattingOptions): string[] {
|
||||
const formattedLines: string[] = [];
|
||||
let indentLevel = 0;
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
let line = lines[i];
|
||||
const trimmedLine = line.trim();
|
||||
|
||||
if (trimmedLine.length === 0) {
|
||||
// 空行保持原样或删除
|
||||
formattedLines.push('');
|
||||
continue;
|
||||
}
|
||||
|
||||
// 检查是否需要减少缩进(遇到右大括号等)
|
||||
if (trimmedLine.startsWith('}') || trimmedLine.startsWith(')') || trimmedLine.startsWith(']')) {
|
||||
indentLevel = Math.max(0, indentLevel - 1);
|
||||
}
|
||||
|
||||
// 添加适当的缩进
|
||||
const indent = this.createIndent(indentLevel, options);
|
||||
const formattedLine = indent + trimmedLine;
|
||||
formattedLines.push(formattedLine);
|
||||
|
||||
// 检查是否需要增加缩进(遇到左大括号等)
|
||||
if (trimmedLine.endsWith('{') || trimmedLine.endsWith('(') || trimmedLine.endsWith('[')) {
|
||||
indentLevel++;
|
||||
}
|
||||
|
||||
// 特殊处理else、catch等关键字,它们应该与前面的右大括号在同一行
|
||||
if (trimmedLine.startsWith('else') || trimmedLine.startsWith('catch') || trimmedLine.startsWith('elif')) {
|
||||
if (formattedLines.length > 1) {
|
||||
const prevLine = formattedLines[formattedLines.length - 2];
|
||||
if (prevLine.trim().endsWith('}')) {
|
||||
// 将else等关键字与前面的右大括号放在同一行
|
||||
formattedLines[formattedLines.length - 2] = prevLine.trim() + ' ' + trimmedLine;
|
||||
formattedLines.pop(); // 移除当前行
|
||||
indentLevel--; // 修正缩进级别
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 规范化空格(在操作符周围添加适当空格)
|
||||
return formattedLines.map(line => this.normalizeSpaces(line));
|
||||
}
|
||||
|
||||
// 在操作符周围添加适当空格
|
||||
private normalizeSpaces(line: string): string {
|
||||
// 在常见的操作符周围添加空格
|
||||
return line
|
||||
.replace(/([^\s])(==|!=|<=|>=|<|>|=|\+|-|\*|\/|%)([^\s])/g, '$1 $2 $3')
|
||||
.replace(/([^\s])(,)([^\s])/g, '$1$2 $3')
|
||||
.replace(/\s+/g, ' ') // 将多个空格替换为单个空格
|
||||
.trim();
|
||||
}
|
||||
|
||||
// 创建指定级别的缩进
|
||||
private createIndent(level: number, options: vscode.FormattingOptions): string {
|
||||
if (options.insertSpaces) {
|
||||
return ' '.repeat(level * options.tabSize);
|
||||
} else {
|
||||
return '\t'.repeat(level);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
import * as vscode from 'vscode';
|
||||
import { beautifyCode, isSquirrelCode } from '../utils/beautifyHelper';
|
||||
|
||||
// 输入时格式化提供者类
|
||||
/**
|
||||
* 输入时格式化提供者类 - 使用 js-beautify.js
|
||||
*/
|
||||
export class OnTypeFormattingProvider implements vscode.OnTypeFormattingEditProvider {
|
||||
// 在用户输入特定字符时自动格式化代码
|
||||
/**
|
||||
* 在用户输入特定字符时自动格式化代码
|
||||
*/
|
||||
async provideOnTypeFormattingEdits(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
@@ -12,138 +17,162 @@ export class OnTypeFormattingProvider implements vscode.OnTypeFormattingEditProv
|
||||
): Promise<vscode.TextEdit[]> {
|
||||
const edits: vscode.TextEdit[] = [];
|
||||
|
||||
// 根据输入的字符执行不同的格式化操作
|
||||
switch (ch) {
|
||||
case ')':
|
||||
// 输入右括号时格式化当前行
|
||||
edits.push(...this.formatCurrentLine(document, position, options));
|
||||
break;
|
||||
case ';':
|
||||
// 输入分号时格式化当前行
|
||||
edits.push(...this.formatCurrentLine(document, position, options));
|
||||
break;
|
||||
case '}':
|
||||
// 输入右大括号时格式化整个代码块
|
||||
edits.push(...this.formatCodeBlock(document, position, options));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
try {
|
||||
// 检查是否是 Squirrel 代码
|
||||
const textBefore = document.getText(new vscode.Range(new vscode.Position(0, 0), position));
|
||||
if (!isSquirrelCode(textBefore)) {
|
||||
return edits;
|
||||
}
|
||||
|
||||
// 根据输入的字符执行不同的格式化操作
|
||||
switch (ch) {
|
||||
case ')':
|
||||
// 输入右括号时格式化当前行
|
||||
edits.push(...this.formatCurrentLine(document, position, options));
|
||||
break;
|
||||
case ';':
|
||||
// 输入分号时格式化当前行
|
||||
edits.push(...this.formatCurrentLine(document, position, options));
|
||||
break;
|
||||
case '}':
|
||||
// 输入右大括号时格式化整个代码块
|
||||
edits.push(...this.formatCodeBlock(document, position, options));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('输入时格式化失败:', error);
|
||||
}
|
||||
|
||||
return edits;
|
||||
}
|
||||
|
||||
// 格式化当前行
|
||||
/**
|
||||
* 使用 js-beautify 格式化当前行
|
||||
*/
|
||||
private formatCurrentLine(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
options: vscode.FormattingOptions
|
||||
): vscode.TextEdit[] {
|
||||
const line = document.lineAt(position.line);
|
||||
const trimmedLine = line.text.trim();
|
||||
const edits: vscode.TextEdit[] = [];
|
||||
|
||||
if (trimmedLine.length === 0) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
// 获取当前行
|
||||
const line = document.lineAt(position.line);
|
||||
const lineText = line.text;
|
||||
|
||||
// 简单的格式化:确保行尾没有多余空格
|
||||
if (line.text !== trimmedLine && !line.text.endsWith(' ')) {
|
||||
const range = new vscode.Range(
|
||||
new vscode.Position(position.line, 0),
|
||||
new vscode.Position(position.line, line.text.length)
|
||||
// 获取当前行的上下文(向前几行,向后几行)
|
||||
const startLine = Math.max(0, position.line - 2);
|
||||
const endLine = Math.min(document.lineCount - 1, position.line + 2);
|
||||
|
||||
const contextText = document.getText(
|
||||
new vscode.Range(
|
||||
new vscode.Position(startLine, 0),
|
||||
new vscode.Position(endLine, document.lineAt(endLine).text.length)
|
||||
)
|
||||
);
|
||||
return [vscode.TextEdit.replace(range, trimmedLine)];
|
||||
|
||||
// 使用 js-beautify 格式化代码块
|
||||
const formattedContext = beautifyCode(contextText, options);
|
||||
|
||||
// 比较原始文本和格式化后的文本
|
||||
if (formattedContext === contextText) {
|
||||
return edits; // 没有变化,不需要编辑
|
||||
}
|
||||
|
||||
// 应用格式化结果
|
||||
const originalLines = contextText.split('\n');
|
||||
const formattedLines = formattedContext.split('\n');
|
||||
|
||||
for (let i = 0; i < originalLines.length && i < formattedLines.length; i++) {
|
||||
const original = originalLines[i];
|
||||
const formatted = formattedLines[i];
|
||||
|
||||
if (original !== formatted) {
|
||||
const lineNumber = startLine + i;
|
||||
const range = new vscode.Range(
|
||||
new vscode.Position(lineNumber, 0),
|
||||
new vscode.Position(lineNumber, document.lineAt(lineNumber).text.length)
|
||||
);
|
||||
edits.push(vscode.TextEdit.replace(range, formatted));
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('格式化当前行失败:', error);
|
||||
}
|
||||
|
||||
return [];
|
||||
return edits;
|
||||
}
|
||||
|
||||
// 格式化代码块
|
||||
/**
|
||||
* 使用 js-beautify 格式化代码块
|
||||
*/
|
||||
private formatCodeBlock(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
options: vscode.FormattingOptions
|
||||
): vscode.TextEdit[] {
|
||||
const edits: vscode.TextEdit[] = [];
|
||||
const line = document.lineAt(position.line);
|
||||
|
||||
// 查找匹配的左大括号
|
||||
let braceCount = 1;
|
||||
let blockStartLine = -1;
|
||||
try {
|
||||
// 查找匹配的左大括号
|
||||
let braceCount = 1;
|
||||
let blockStartLine = -1;
|
||||
|
||||
for (let i = position.line - 1; i >= 0; i--) {
|
||||
const currentLine = document.lineAt(i);
|
||||
const lineText = currentLine.text;
|
||||
for (let i = position.line - 1; i >= 0; i--) {
|
||||
const currentLine = document.lineAt(i);
|
||||
const lineText = currentLine.text;
|
||||
|
||||
for (let j = lineText.length - 1; j >= 0; j--) {
|
||||
if (lineText[j] === '}') {
|
||||
braceCount++;
|
||||
} else if (lineText[j] === '{') {
|
||||
braceCount--;
|
||||
if (braceCount === 0) {
|
||||
blockStartLine = i;
|
||||
break;
|
||||
for (let j = lineText.length - 1; j >= 0; j--) {
|
||||
if (lineText[j] === '}') {
|
||||
braceCount++;
|
||||
} else if (lineText[j] === '{') {
|
||||
braceCount--;
|
||||
if (braceCount === 0) {
|
||||
blockStartLine = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (blockStartLine !== -1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (blockStartLine !== -1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 获取代码块的范围
|
||||
const endLine = position.line;
|
||||
const blockText = document.getText(
|
||||
new vscode.Range(
|
||||
new vscode.Position(blockStartLine, 0),
|
||||
new vscode.Position(endLine + 1, 0) // 包含右大括号行
|
||||
)
|
||||
);
|
||||
|
||||
if (blockStartLine !== -1) {
|
||||
// 调整代码块的缩进
|
||||
const startLine = document.lineAt(blockStartLine);
|
||||
const startIndent = this.getIndentLevel(startLine.text);
|
||||
// 使用 js-beautify 格式化代码块
|
||||
const formattedBlock = beautifyCode(blockText, options);
|
||||
|
||||
for (let i = blockStartLine + 1; i < position.line; i++) {
|
||||
const currentLine = document.lineAt(i);
|
||||
const currentIndent = this.getIndentLevel(currentLine.text);
|
||||
|
||||
if (currentIndent < startIndent + 1) {
|
||||
const newIndent = this.createIndent(startIndent + 1, options);
|
||||
const range = new vscode.Range(
|
||||
new vscode.Position(i, 0),
|
||||
new vscode.Position(i, currentIndent)
|
||||
);
|
||||
edits.push(vscode.TextEdit.replace(range, newIndent));
|
||||
if (formattedBlock === blockText) {
|
||||
return edits; // 没有变化
|
||||
}
|
||||
|
||||
// 应用格式化结果
|
||||
const range = new vscode.Range(
|
||||
new vscode.Position(blockStartLine, 0),
|
||||
new vscode.Position(endLine + 1, 0)
|
||||
);
|
||||
edits.push(vscode.TextEdit.replace(range, formattedBlock));
|
||||
}
|
||||
|
||||
// 调整右大括号的缩进
|
||||
const endIndent = this.createIndent(startIndent, options);
|
||||
const endRange = new vscode.Range(
|
||||
new vscode.Position(position.line, 0),
|
||||
new vscode.Position(position.line, this.getIndentLevel(line.text))
|
||||
);
|
||||
edits.push(vscode.TextEdit.replace(endRange, endIndent));
|
||||
} catch (error) {
|
||||
console.error('格式化代码块失败:', error);
|
||||
}
|
||||
|
||||
return edits;
|
||||
}
|
||||
|
||||
// 获取行的缩进级别
|
||||
private getIndentLevel(line: string): number {
|
||||
let indent = 0;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
if (line[i] === ' ') {
|
||||
indent++;
|
||||
} else if (line[i] === '\t') {
|
||||
indent += 4; // 假设一个tab等于4个空格
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return indent;
|
||||
}
|
||||
|
||||
// 创建指定级别的缩进
|
||||
private createIndent(level: number, options: vscode.FormattingOptions): string {
|
||||
if (options.insertSpaces) {
|
||||
return ' '.repeat(level);
|
||||
} else {
|
||||
return '\t'.repeat(Math.floor(level / 4)); // 假设一个tab等于4个空格
|
||||
}
|
||||
}
|
||||
}
|
||||
228
src/utils/beautifyHelper.ts
Normal file
228
src/utils/beautifyHelper.ts
Normal file
@@ -0,0 +1,228 @@
|
||||
import * as vscode from 'vscode';
|
||||
|
||||
// 由于 js-beautify.js 文件体积较大且复杂,我们将创建专门的存根函数
|
||||
// 将使用原生的 js-beautify 功能
|
||||
|
||||
let _jsBeauifyInstance: any = null;
|
||||
|
||||
/**
|
||||
* 动态创建 js_beautify 函数
|
||||
*/
|
||||
function createJsBeautify(): any {
|
||||
if (_jsBeauifyInstance) {
|
||||
return _jsBeauifyInstance;
|
||||
}
|
||||
|
||||
try {
|
||||
// 加载原始的 js-beautify.js 文件
|
||||
const beautifyModule = loadJsBeautify();
|
||||
_jsBeauifyInstance = beautifyModule;
|
||||
return _jsBeauifyInstance;
|
||||
} catch (error) {
|
||||
console.error('加载 js-beautify 失败,使用后备实现:', error);
|
||||
// 调用后备实现
|
||||
return createBasicJsBeautify();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 js-beautify 模块
|
||||
*/
|
||||
function loadJsBeautify(): any {
|
||||
// 根据环境动态加载
|
||||
try {
|
||||
// 尝试 require 原始的 js-beautify.js 文件
|
||||
// 注意:TypeScript 会从 ./dist 目录运行,所以需要从正确的路径加载
|
||||
const beautifyPath = __dirname + '/../../js-beautify.js';
|
||||
const Module = require('module');
|
||||
const vm = require('vm');
|
||||
const fs = require('fs');
|
||||
|
||||
// 读取文件内容
|
||||
const code = fs.readFileSync(beautifyPath, 'utf8');
|
||||
|
||||
// 设置全局环境
|
||||
const sandbox: any = {
|
||||
window: {},
|
||||
global: {},
|
||||
console: console,
|
||||
String: String,
|
||||
Array: Array,
|
||||
Object: Object,
|
||||
Math: Math
|
||||
};
|
||||
|
||||
// 在沙箱中执行代码
|
||||
const script = new vm.Script(code);
|
||||
const context = vm.createContext(sandbox);
|
||||
script.runInContext(context);
|
||||
|
||||
// 获取 js_beautify 函数
|
||||
return context.window.js_beautify || context.js_beautify || sandbox.window.js_beautify;
|
||||
} catch (loadError) {
|
||||
console.error('无法加载原始 js-beautify, 错误:', loadError);
|
||||
throw loadError;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 基础的 js-beautify 实现(后备方案)
|
||||
*/
|
||||
function createBasicJsBeautify(): any {
|
||||
return function(code: string, options: any = {}): string {
|
||||
// 默认选项
|
||||
const defaultOptions = {
|
||||
indent_size: 4,
|
||||
indent_char: ' ',
|
||||
preserve_newlines: true,
|
||||
brace_style: 'collapse',
|
||||
space_before_conditional: true,
|
||||
space_after_anon_function: false,
|
||||
wrap_line_length: 120,
|
||||
end_with_newline: false
|
||||
};
|
||||
|
||||
// 合并选项
|
||||
const opts = { ...defaultOptions, ...options };
|
||||
|
||||
// 简化的代码美化实现
|
||||
let formatted = code;
|
||||
|
||||
// 清理缩进
|
||||
formatted = formatted.replace(/[\r\n]+/g, '\n');
|
||||
|
||||
const lines = formatted.split('\n');
|
||||
const result: string[] = [];
|
||||
let indentLevel = 0;
|
||||
const indentStr = opts.indent_char.repeat(opts.indent_size);
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
|
||||
// 跳过空行
|
||||
if (trimmed.length === 0) {
|
||||
result.push('');
|
||||
continue;
|
||||
}
|
||||
|
||||
// 处理大括号
|
||||
if (trimmed.startsWith('}') || trimmed.startsWith(')') || trimmed.startsWith(']')) {
|
||||
indentLevel = Math.max(0, indentLevel - 1);
|
||||
}
|
||||
|
||||
// 添加缩进
|
||||
const indentedLine = indentStr.repeat(indentLevel) + trimmed;
|
||||
result.push(indentedLine);
|
||||
|
||||
// 增加缩进
|
||||
if (trimmed.endsWith('{') || trimmed.endsWith('(') || trimmed.endsWith('[')) {
|
||||
indentLevel++;
|
||||
}
|
||||
|
||||
// 特殊处理 else、catch 等关键字
|
||||
if (trimmed.startsWith('else') || trimmed.startsWith('catch') || trimmed.startsWith('elif')) {
|
||||
// 检查前面一行是否以 } 结尾
|
||||
if (result.length > 1) {
|
||||
const prevLine = result[result.length - 2];
|
||||
const prevTrimmed = prevLine.trim();
|
||||
if (prevTrimmed.endsWith('}')) {
|
||||
// 移动到前一行的必要部分
|
||||
result[result.length - 2] = indentStr.repeat(indentLevel - 1) +
|
||||
prevTrimmed + ' ' + trimmed;
|
||||
result.pop(); // 移除当前行
|
||||
indentLevel--; // 修正缩进级别
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let finalResult = result.join('\n');
|
||||
|
||||
// 处理空格 - 在操作符周围添加空格
|
||||
finalResult = finalResult
|
||||
.replace(/([a-zA-Z0-9_$])([=!<>+\-*/%])([a-zA-Z0-9_$])/g, '$1 $2 $3')
|
||||
.replace(/([a-zA-Z0-9_$])(,)([a-zA-Z0-9_$])/g, '$1$2 $3')
|
||||
.replace(/\s+/g, ' ') // 将多个空格替换为单个空格
|
||||
.trim();
|
||||
|
||||
return finalResult;
|
||||
};
|
||||
}
|
||||
|
||||
// 初始化 js_beautify
|
||||
const jsBeautify = {
|
||||
js_beautify: createJsBeautify()
|
||||
};
|
||||
|
||||
/**
|
||||
* Squirrel 语言的 js-beautify 选项配置
|
||||
*/
|
||||
export function getSquirrelBeautifyOptions(options: vscode.FormattingOptions): any {
|
||||
return {
|
||||
indent_size: options.tabSize,
|
||||
indent_char: options.insertSpaces ? ' ' : '\t',
|
||||
preserve_newlines: true,
|
||||
max_preserve_newlines: 2,
|
||||
jslint_happy: false,
|
||||
brace_style: "collapse",
|
||||
space_before_conditional: true,
|
||||
space_after_anon_function: false,
|
||||
unescape_strings: false,
|
||||
wrap_line_length: 120,
|
||||
end_with_newline: false
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 js-beautify 格式化代码
|
||||
*/
|
||||
export function beautifyCode(code: string, options: vscode.FormattingOptions): string {
|
||||
if (!jsBeautify || !jsBeautify.js_beautify) {
|
||||
console.warn('js-beautify 不可用,返回原始代码');
|
||||
return code;
|
||||
}
|
||||
|
||||
try {
|
||||
const beautifyOptions = getSquirrelBeautifyOptions(options);
|
||||
|
||||
// 检查代码长度,处理大块代码
|
||||
const maxChunkSize = 50000; // 50KB 每块
|
||||
if (code.length > maxChunkSize) {
|
||||
// 分割代码并分块处理
|
||||
const chunks = code.split('\n');
|
||||
const resultChunks: string[] = [];
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const formattedChunk = jsBeautify.js_beautify(chunk, beautifyOptions);
|
||||
resultChunks.push(formattedChunk);
|
||||
}
|
||||
|
||||
return resultChunks.join('\n');
|
||||
}
|
||||
|
||||
// 直接格式化小代码块
|
||||
return jsBeautify.js_beautify(code, beautifyOptions);
|
||||
} catch (error) {
|
||||
console.error('js-beautify 格式化失败:', error);
|
||||
// 如果格式化失败,返回原始代码
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测是否为 Squirrel 代码(用于确定是否应用格式化)
|
||||
*/
|
||||
export function isSquirrelCode(code: string): boolean {
|
||||
// 简单的启发式检测 - Squirrel 特有关键字
|
||||
const squirrelKeywords = [
|
||||
'function', 'local', 'if', 'else', 'while', 'for', 'foreach',
|
||||
'class', 'constructor', 'extends', 'instanceof', 'in',
|
||||
'try', 'catch', 'throw', 'clone', 'delegate', 'resume', 'yield',
|
||||
'typeof', 'member', 'rawcall', 'call', 'setdebughook'
|
||||
];
|
||||
|
||||
// 提高检测准确性 - 需要至少匹配到1个关键字
|
||||
return squirrelKeywords.some(keyword =>
|
||||
new RegExp(`\\b${keyword}\\b`).test(code)
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user