Code Formatter
Format, beautify, and inspect source code across 15+ languages with syntax auto-detection, configurable indentation and quote rules, and line-by-line diffing.
All formatting runs 100% locally in your browser — your code never leaves your device.
How to Format Code Online
- Paste your source code or SQL query into the Input editor, or drag and drop a source file from your local workspace.
- Verify the auto-detected language badge in the toolbar, or manually choose a language from the dropdown menu.
- Adjust formatting parameters: indent size (2 spaces, 4 spaces, or Tabs), maximum print width, quote delimiters, semicolon insertion, and trailing commas.
- Inspect formatting changes in the Diff tab or copy the formatted result directly to your clipboard or download it as a source file.
Real-World Formatting Comparisons
Interactive before-and-after benchmarks across distinct syntax models:
JavaScript: Minified Async Handler → Structured ES6+
Original (Single-Line Minified)
const fetchUserData=async(userId)=>{try{const res=await fetch(`/api/users/${userId}`);if(!res.ok)throw new Error('Network error');const data=await res.json();return{id:data.id,name:data.name,roles:data.roles.filter(r=>r.active)};}catch(err){console.error('Fetch failure:',err);return null;}};Formatted Output (2 Spaces, Trailing Commas)
const fetchUserData = async (userId) => {
try {
const res = await fetch(`/api/users/${userId}`);
if (!res.ok) throw new Error('Network error');
const data = await res.json();
return {
id: data.id,
name: data.name,
roles: data.roles.filter((r) => r.active),
};
} catch (err) {
console.error('Fetch failure:', err);
return null;
}
};Supported Language Engines & Grammar Models
The formatter selects syntax-specific tokenizers to guarantee that language-specific semantics are preserved during beautification.
| Language Family | Supported Targets | Parser Engine | Formatting & Safety Mechanics |
|---|---|---|---|
| ECMAScript & Web Scripting | JavaScript (ES2024, JSX), TypeScript | Lexical tokenizer & indentation engine (js-beautify) | Configurable indentation, semicolons, quote normalization, line wrapping, block formatting |
| Structured Data & Serialization | JSON | Strict RFC 8259 parser & recursive serializer | Mandatory double quotes, no trailing commas, structural key-value alignment, syntax validation |
| Stylesheets & Preprocessors | CSS, SCSS, Less | Declaration block tokenizer | Selector hierarchy nesting, property colon alignment, variable spacing, semicolon enforcement |
| Relational Database Queries | SQL (ANSI, MySQL, PostgreSQL, SQLite, T-SQL) | Clause-driven recursive statement parser | Major clause line breaking (SELECT, FROM, WHERE, GROUP BY), join indentation, operator alignment |
| Whitespace-Significant Scripting | Python | Indentation stack-aware tokenizer | PEP 8 4-space indentation normalization, colon scope boundary preservation, trailing whitespace trimming |
| Markup & Documentation | HTML5, Markdown | HTML hierarchy beautifier & Markdown layout normalizer | Tag hierarchy nesting, void tag safety, fenced code block preservation, list indentation alignment |
| Compiled & Systems Languages | Java, C#, C++, Go, PHP | C-style scope & syntax beautifier | Brace balancing, control flow statement indentation, method boundary spacing |
Formatting Rules & Engineering Tradeoffs
Formatting options directly affect codebase maintainability, Git blame stability, and language runtime semantics.
| Option | Choices | Engine Behavior | Practical Tradeoffs & Git Impact |
|---|---|---|---|
| Indentation | 2 spaces / 4 spaces / Tabs | Replaces leading whitespace on every line according to computed scope depth. | 2 spaces is standard in JS/TS/HTML (saves horizontal space for deep callbacks). 4 spaces is standard in Python (PEP 8), Java, and C++. Tabs decouple visual width from source bytes, allowing each developer to set tab size in their editor. |
| Line Width (Print Width) | 80 / 100 / 120 chars | Soft-wraps argument lists, attributes, and chained expressions when exceeding character threshold. | 80 chars fits two files side-by-side on 1080p screens and mobile code reviews. 100/120 chars reduces artificial line splits in modern wide-screen IDEs and high-resolution displays. |
| Quote Style | Preserve / Single (') / Double (") | Safely normalizes string literal delimiters. Skips conversion if target quote would require escaping inner characters. | Single quotes are prevalent in TypeScript and frontend apps to distinguish JS strings from HTML attributes. Double quotes are mandatory in JSON (RFC 8259) and standard in Python and C-family languages. |
| Semicolons | Preserve / On (Insert) / Off (Remove) | Inserts semicolons at statement terminators or removes them where safe according to ECMAScript grammar. | Explicit semicolons prevent subtle Automatic Semicolon Insertion (ASI) bugs on lines beginning with `(`, `[`, `/`, or template literals. Semicolon-free syntax yields cleaner, less visually cluttered code. |
| Trailing Commas | Preserve / None / ES5 / All | Adds or strips commas following the final item in multiline arrays, objects, parameters, and imports. | Trailing commas produce cleaner Git diffs: adding a new element modifies only 1 line instead of editing the previous line to add a comma. "All" covers function parameters (ES2017+); "ES5" limits to objects and arrays. |
Under the Hood: AST-Based Printing vs. Token-Stream Beautification
Token-Stream Transformation & Context Preservation
Unlike compilers that discard comments and whitespace, token-stream formatters scan lexical tokens sequentially. Block indentation is computed using a depth counter incremented at opening delimiters ({, (, [) and decremented at closing tokens.
This approach preserves intentional developer formatting choices—such as intentional blank lines between logic blocks, inline JSDoc comments, and SQL optimizer hints—without rewriting expression trees.
AST Safety Guards & Quote Normalization
When normalizing string quotes, the engine inspects string content for existing delimiter characters. A double-quoted string containing literal single quotes (e.g. "it's valid") is never converted to single quotes unless inner quotes can be cleanly escaped without creating backslash clutter.
For structured formats like JSON, full RFC 8259 validation executes prior to printing, ensuring that syntactically malformed objects trigger helpful syntax warnings rather than being corrupted into invalid structures.
Core Engineering Applications in Production Systems
- De-obfuscating Production Bundles During Incidents: When diagnosing production exceptions reported by Sentry or Datadog where source maps are missing or misaligned, minified code runs together on a single line. Re-formatting the bundle snippet reveals control flow, un-nests ternary operators, and allows mapping column offsets to logical variables.
- Sanitizing Raw Database Query Logs for EXPLAIN Plans: ORM query loggers (Prisma, TypeORM, Hibernate) output multi-table JOIN queries as unindented single-line strings. Beautifying them creates structured relational clauses (FROM, WHERE, GROUP BY), making query bottlenecks readable before running EXPLAIN ANALYZE.
- Pre-Commit Code Review & LCS Diff Verification: Before staging code into Git, running external or AI-generated snippets through the formatter and switching to the Diff tab highlights exactly which lines changed. This ensures no unexpected deletions or unintended logic alterations slip into pull requests.
- Standardizing Documentation & RFC Snippets: Pasting code from disparate sources into internal wikis, OpenAPI documentation, or technical RFCs often introduces inconsistent indentation and mixed quotation styles. Normalizing snippets to a unified print width and indent width maintains professional consistency.
Frequently Asked Questions
What is the technical difference between code formatting and code minification?
Code formatting (beautification) and minification are inverted operations. A code formatter parses lexical tokens to insert structured indentation, standardized line wraps, and consistent spacing so source code is readable, maintainable, and verifiable by human engineers. In contrast, a minifier aggressively removes all comments, strips non-essential whitespace, and shortens variable identifiers to reduce file size over network transfers.
Can formatting minified code restore original variable names and project structure?
Formatting un-nests compressed statements, aligns curly braces, and breaks single-line bundles into readable lines, allowing engineers to trace execution flow and inspect variable assignments during production debugging. However, it cannot reconstruct original variable or function names that were renamed (mangled) by compilers like Terser or esbuild; restoring original identifier names requires matching source maps (.map files).
Tabs vs. Spaces: Which indentation setting should I use?
Spaces (2 or 4) provide rigid visual consistency across all environments, guaranteeing code looks identical in Git diff viewers, code reviews, and terminals. 2 spaces is standard across JavaScript, TypeScript, and HTML; 4 spaces is standard in Python (PEP 8), Java, and C++. Tabs offer superior accessibility: developers can customize tab stop widths in their IDE without altering source files, and tabs consume fewer bytes.
What are Automatic Semicolon Insertion (ASI) hazards in JavaScript, and how does the semicolon option protect code?
JavaScript parsers automatically insert virtual semicolons at statement boundaries. However, ASI fails when a new line begins with characters like `[`, `(`, `/`, `+`, `-`, or backticks, causing the runtime to interpret the line as an argument or index of the previous expression (e.g., `return\n{ status: true }` returns undefined). Setting Semicolons to "On" explicitly terminates statements to eliminate ASI runtime bugs, while "Off" removes them for clean StandardJS compliance.
Why do modern coding standards enforce trailing commas in multiline structures?
In multiline arrays, object literals, imports, and function arguments, adding a new item without trailing commas requires modifying two lines: appending a comma to the existing final item and writing the new line. This marks the previous line as modified in git diff and pollutes git blame history. Enabling trailing commas guarantees that future additions or deletions only touch the exact line being changed.
Can formatting source code alter program logic or break string literals?
No. The formatting engine treats strings, template literals, and regular expressions as atomic, immutable tokens. Quote style conversion only occurs when inner characters contain no unescaped delimiters of the target quote, avoiding syntax breaks. Code semantics, variable bindings, and arithmetic precedence remain completely unchanged.
How does the Diff tab help verify changes before applying them to a codebase?
The Diff tab executes a line-by-line Myers Longest Common Subsequence (LCS) comparison between the unformatted raw input and the beautified output. It highlights added lines in green and removed whitespace in red, allowing developers to visually audit every structural adjustment before copying code or committing changes to version control.
How does the formatter handle compound files like HTML with embedded JavaScript and CSS?
The HTML formatter operates hierarchically: it formats top-level markup elements and identifies `<script>` and `<style>` blocks. The contents of these tags are delegated to dedicated JavaScript and CSS formatting sub-engines, indented relative to their parent container tag, and reassembled into a cohesive, properly nested document.
