代码格式化工具

这个工具可以帮助您格式化和美化各种编程语言的代码,使其更易于阅读和维护。支持多种语言和格式化选项。

提示:选择合适的编程语言后,点击格式化按钮即可美化您的代码。

关于代码格式化工具

代码格式化是提高代码可读性和可维护性的重要步骤。格式良好的代码更易于理解、调试和协作开发。

使用此工具,您可以:

  • 美化和格式化各种编程语言的代码
  • 调整代码缩进和样式
  • 压缩代码以减小文件体积
  • 快速复制格式化后的代码

所有处理都在您的浏览器中完成,您的代码不会发送到服务器,保证数据安全。

`; codeEditor.setValue(exampleCode); // 语言选择器 const languageSelect = document.getElementById('language-select'); languageSelect.addEventListener('change', function() { codeEditor.setOption('mode', this.value); updateExampleCode(this.value); }); // 主题选择器 const themeSelect = document.getElementById('theme-select'); themeSelect.addEventListener('change', function() { codeEditor.setOption('theme', this.value); }); // 缩进选择器 const indentSelect = document.getElementById('indent-select'); indentSelect.addEventListener('change', function() { const value = this.value; if (value === 'tab') { codeEditor.setOption('indentWithTabs', true); codeEditor.setOption('indentUnit', 4); } else { codeEditor.setOption('indentWithTabs', false); codeEditor.setOption('indentUnit', parseInt(value)); } }); // 格式化按钮 document.getElementById('format-btn').addEventListener('click', function() { try { const code = codeEditor.getValue(); const language = languageSelect.value; const indentSize = indentSelect.value === 'tab' ? 'tab' : parseInt(indentSelect.value); let formattedCode = code; // 根据不同语言使用不同的格式化方法 if (language === 'htmlmixed' || language === 'xml') { formattedCode = html_beautify(code, { indent_size: indentSize === 'tab' ? 1 : indentSize, indent_with_tabs: indentSize === 'tab', wrap_line_length: 0 }); } else if (language === 'css') { formattedCode = css_beautify(code, { indent_size: indentSize === 'tab' ? 1 : indentSize, indent_with_tabs: indentSize === 'tab' }); } else if (language === 'javascript' || language === 'jsx' || language === 'typescript' || language === 'json') { formattedCode = js_beautify(code, { indent_size: indentSize === 'tab' ? 1 : indentSize, indent_with_tabs: indentSize === 'tab', preserve_newlines: true, max_preserve_newlines: 2, space_in_paren: false, space_in_empty_paren: false, brace_style: 'collapse' }); } codeEditor.setValue(formattedCode); hideError(); } catch (err) { showError(err.toString()); } }); // 压缩按钮 document.getElementById('minify-btn').addEventListener('click', function() { try { const code = codeEditor.getValue(); const language = languageSelect.value; let minifiedCode = code; // 简单的压缩实现 minifiedCode = code .replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '') // 移除注释 .replace(/\s+/g, ' ') // 将多个空白字符替换为单个空格 .replace(/\s*([{}:;,])\s*/g, '$1') // 移除括号、冒号、分号、逗号周围的空白 .replace(/;\s*}/g, '}') // 移除最后一个分号 .trim(); // 移除首尾空白 codeEditor.setValue(minifiedCode); hideError(); } catch (err) { showError(err.toString()); } }); // 复制按钮 document.getElementById('copy-btn').addEventListener('click', function() { try { const code = codeEditor.getValue(); navigator.clipboard.writeText(code).then(function() { alert('代码已复制到剪贴板!'); }).catch(function(err) { showError('复制失败: ' + err); }); } catch (err) { showError(err.toString()); } }); // 清空按钮 document.getElementById('clear-btn').addEventListener('click', function() { codeEditor.setValue(''); hideError(); }); // 根据选择的语言更新示例代码 function updateExampleCode(language) { let exampleCode = ''; switch (language) { case 'htmlmixed': exampleCode = ` 示例页面

欢迎使用代码格式化工具

这是一个示例HTML代码,您可以尝试格式化它。

`; break; case 'css': exampleCode = `.container{max-width:1200px;margin:0 auto;} .header{background-color:#f0f0f0;padding:10px;} .content{padding:20px 0;} .button{display:inline-block;padding:10px 15px;background-color:#4CAF50;color:white;border:none;border-radius:4px;cursor:pointer;font-size:16px;} .button:hover{background-color:#45a049;} @media (max-width: 768px) { .container{padding:0 15px;} .header{padding:5px;} }`; break; case 'javascript': case 'jsx': case 'typescript': exampleCode = `function calculateTotal(items) { return items.reduce(function(total, item) { var price = item.price; var quantity = item.quantity; return total + price * quantity; }, 0); } var shoppingCart = [ {name: "产品1", price: 100, quantity: 2}, {name: "产品2", price: 50, quantity: 1}, {name: "产品3", price: 200, quantity: 3} ]; var total = calculateTotal(shoppingCart); console.log("总价: ¥" + total); // 异步函数示例 async function fetchUserData(userId) { try { var url = "https://api.example.com/users/" + userId; var response = await fetch(url); if (!response.ok) { throw new Error('获取用户数据失败'); } var userData = await response.json(); return userData; } catch (error) { console.error(error); return null; } }`; break; case 'php': exampleCode = `用户名: 张三\n邮箱: [email protected]\narray(2) { ["name"]=> string(6) "张三" ["email"]=> string(20) "[email protected]" } `; break; case 'python': exampleCode = `import random import math from datetime import datetime class Calculator: def __init__(self, name): self.name = name self.history = [] def add(self, a, b): result = a + b self.history.append("{} + {} = {}".format(a, b, result)) return result def subtract(self, a, b): result = a - b self.history.append("{} - {} = {}".format(a, b, result)) return result def multiply(self, a, b): result = a * b self.history.append("{} * {} = {}".format(a, b, result)) return result def divide(self, a, b): if b == 0: raise ValueError("除数不能为零") result = a / b self.history.append("{} / {} = {}".format(a, b, result)) return result def get_history(self): return self.history # 创建计算器实例 calc = Calculator("我的计算器") print("计算器名称: {}".format(calc.name)) # 执行一些计算 print("1 + 2 = {}".format(calc.add(1, 2))) print("5 - 3 = {}".format(calc.subtract(5, 3))) print("4 * 6 = {}".format(calc.multiply(4, 6))) print("10 / 2 = {}".format(calc.divide(10, 2))) # 打印计算历史 print("\\n计算历史:") for item in calc.get_history(): print("- {}".format(item))`; break; case 'java': exampleCode = `import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List products = new ArrayList<>(); products.add(new Product("手机", 3999.0, 10)); products.add(new Product("笔记本电脑", 6999.0, 5)); products.add(new Product("耳机", 299.0, 20)); products.add(new Product("键盘", 199.0, 15)); // 使用流过滤和处理数据 List expensiveProducts = products.stream() .filter(p -> p.getPrice() > 1000) .collect(Collectors.toList()); System.out.println("价格超过1000元的产品:"); for (Product p : expensiveProducts) { System.out.println(p); } // 计算总库存价值 double totalValue = products.stream() .mapToDouble(p -> p.getPrice() * p.getQuantity()) .sum(); System.out.println("\\n总库存价值: " + totalValue + "元"); } } class Product { private String name; private double price; private int quantity; public Product(String name, double price, int quantity) { this.name = name; this.price = price; this.quantity = quantity; } public String getName() { return name; } public double getPrice() { return price; } public int getQuantity() { return quantity; } @Override public String toString() { return name + " - 价格: " + price + "元, 库存: " + quantity; } }`; break; case 'sql': exampleCode = `-- 创建用户表 CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(100) NOT NULL UNIQUE, password_hash VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ); -- 创建文章表 CREATE TABLE articles ( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(200) NOT NULL, content TEXT NOT NULL, user_id INT NOT NULL, status ENUM('draft', 'published', 'archived') DEFAULT 'draft', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ); -- 插入一些测试数据 INSERT INTO users (username, email, password_hash) VALUES ('zhangsan', '[email protected]', 'hashed_password_1'), ('lisi', '[email protected]', 'hashed_password_2'); -- 查询示例 SELECT a.id, a.title, a.status, u.username AS author, a.created_at FROM articles a JOIN users u ON a.user_id = u.id WHERE a.status = 'published' ORDER BY a.created_at DESC LIMIT 10;`; break; case 'json': exampleCode = `{ "name": "代码格式化工具", "version": "1.0.0", "description": "一个简单易用的代码格式化工具", "features": [ "支持多种编程语言", "自定义缩进选项", "代码高亮显示", "代码压缩功能" ], "languages": { "html": true, "css": true, "javascript": true, "php": true, "python": true, "java": true, "sql": true }, "settings": { "theme": "default", "indentSize": 4, "useTabs": false, "lineWrapping": true }, "stats": { "users": 1000, "rating": 4.8, "downloads": 5000 } }`; break; default: exampleCode = '// 请选择一种编程语言,然后在这里输入您的代码'; } codeEditor.setValue(exampleCode); } // 错误处理函数 function showError(message) { const errorElement = document.getElementById('error-message'); errorElement.textContent = '错误: ' + message; errorElement.style.display = 'block'; } function hideError() { const errorElement = document.getElementById('error-message'); errorElement.style.display = 'none'; } });