Code Formatting & Online Runner Guide

Formatting, validating and trying code online cover most of what you do with a snippet day to day. This page spells out where each stops and tabulates the style choices teams argue about most: indentation, quotes and semicolons.

How It Works

Code formatting is the convention for indentation, spacing, line breaks and quotes. Consistent style lets a diff focus on logic changes rather than formatting noise and lowers cognitive load in team work.

Modern projects use Prettier, gofmt, Black and similar tools to auto-format on save or in a pre-commit hook, taking style debates off the table. A linter (e.g. ESLint) goes further and catches likely bugs and code smells.

When to Use This Table

This table is for choosing a formatter or linter for a language. It lists prettier, eslint, rustfmt, gofmt, clang-format and similar tools with what each does, when to reach for it and what to watch out for. Confirm the project existing conventions before choosing.

When not to consult it: you are designing a code style guide or debating the boundary between formatting and linting. The two are often conflated — formatting handles layout such as indentation, quotes and line breaks, while linting handles convention and likely defects such as unused variables and dangerous patterns. They can be chosen independently.

Rule of thumb: start from the convention already in the project. Never introduce a second formatter into an existing codebase, because that produces a large diff of meaningless changes. Read the config files (.prettierrc, .eslintrc, rustfmt.toml, .editorconfig) to learn the current state, and only choose when starting a project or unifying several.

Mind the order of execution: format first, then lint. Formatting changes code shape — expanding a single-line if into multiple lines, for instance — so linting first reports line numbers and problems that are already stale, and the editor highlights the wrong location.

Boundaries and Common Pitfalls

  • Overlapping formatter and lint rules fight each other

    A typical conflict: prettier decides whether to use semicolons while an eslint rule also governs them, and prettier picks the print width while max-len also checks it. When the two configurations disagree, lint flags something, the fix is reverted by the formatter, and you loop. The fix is a clear division of labour: leave layout rules (indent, quotes, semi, max-len) to the formatter and disable them in the linter, and keep semantic rules (no-unused-vars, eqeqeeq) in the linter. ESLint --fix mitigates but does not cure overlapping config.

  • First adopting a formatter produces a large unrelated diff

    Running prettier in a repository that was never formatted can change hundreds of files and tens of thousands of lines, mixing real logic changes with pure formatting churn so that review becomes impossible and blame history is polluted. The convention is a dedicated formatting-only commit, kept separate from functional changes; a safer approach is to format in batches per directory and use .git-blame-ignore-revs to mark those commits so git blame skips them.

  • Inconsistent editor formatting config silently overrides each other

    In one project, editor plugins, .editorconfig, format-on-save hooks and pre-commit hooks can each hold a different configuration, and the eventual result differs from what the editor shows. The typical symptom is that saving produces different code than expected. The cure is a single formatting entry point (pre-commit or CI), with .editorconfig holding the shared basics, and editor plugins matching the hooks — documented in the README.

How This Relates to Neighbours

To actually format code, use the in-site formatting tools; this page is a selection reference.

Designing a project style guide (indentation, naming, commit messages) is an engineering convention question, out of scope here.

Configuring lint rule sets and CI checks belongs to continuous integration and is a separate chain from formatting.

If the goal is settling a formatting dispute, read the existing config files and .editorconfig first, then discuss tool choice.

Practical Snippet

Key points: (1) leave layout rules (indent, quotes, semi, max-len) to the formatter and disable them in the linter — when both govern them, lint flags something the formatter reverts, producing a loop; (2) the first adoption of a formatter should be a dedicated formatting-only commit, ideally marked in .git-blame-ignore-revs so it does not pollute blame; (3) always format before lint, because formatting changes code shape and makes earlier lint reports stale; (4) never introduce a second formatter into an existing project; (5) keep a single formatting entry point (pre-commit or CI) with .editorconfig holding the shared basics.

// ① .prettierrc —— 只管布局,不掺语义规则
{
  "semi": false,
  "singleQuote": true,
  "printWidth": 100,
  "trailingComma": "all",
  "arrowParens": "always"
}

// ② .eslintrc —— 语义规则;布局类交给 prettier 并显式关闭,避免互相打架
{
  "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
  "prettier/prettier": "off",
  "rules": {
    "semi": "off",
    "quotes": "off",
    "max-len": "off",
    "@typescript-eslint/no-unused-vars": "error",
    "@typescript-eslint/no-explicit-any": "warn",
    "eqeqeq": ["error", "always"]
  }
}

// ③ 执行顺序:先格式化,再 lint
// package.json
{
  "scripts": {
    "format": "prettier --write .",
    "lint": "eslint . --ext .ts,.vue",
    "fix": "npm run format && npm run lint -- --fix",
    "prepare": "husky && husky install",
    "pre-commit": "lint-staged"
  },
  "lint-staged": {
    "*.{ts,vue}": ["prettier --write", "eslint --fix"]
  }
}

// ④ .git-blame-ignore-revs —— 纯格式化提交不污染 blame
// ① 找到那次格式化提交:git log --format='%H %s' | grep -i format
// ② 写进文件(每行一个 commit)
// ③ 生效:git config blame.ignoreRevsFile .git-blame-ignore-revs

// ⑤ .editorconfig —— 跨编辑器的基础约定
// root = true
// [*]
// indent_style = space
// indent_size = 2
// end_of_line = lf
// insert_final_newline = true
// charset = utf-8

Practical Notes

  • A formatter can bury the real diffWithout agreed rules, one formatting commit can touch thousands of lines and drown the actual logic change. Roll formatting out as a standalone commit first, make functional changes after, and enforce it in pre-commit.
  • Formatting XML/HTML is not a safe round-tripReformatting alters whitespace nodes, and in XML whitespace can be data (content inside <pre>, trailing spaces in text nodes). Documents with significant whitespace should not be automatically reflowed.
  • Indent width is a readability contract, not a preferenceMixing 2 and 4 spaces in one repository confuses editor auto-detection and produces indent-only noise diffs. Unify with .editorconfig and run the formatter on save rather than relying on discipline.

Data Sources

  • Language style guides (PEP 8, Google Style Guides)
  • EditorConfig specification

Codes, names and definitions above come from public specifications; we claim no originality over the specification data itself. The arrangement, Chinese annotations and practical notes on this page are written by us.

Three Tools Compared

ToolWhat It DoesTypical UseWatch Out
XML FormatterRe-indent and validate XML structureAPI payloads, config files, SOAP responsesUnclosed tags are reported as errors
JS FormatterNormalise indentation, quotes, semicolons and line breaksInheriting code, unifying style before a mergeLayout only, never semantics; confirm the semicolon rule first
JS RunnerExecute snippets in the browser and inspect outputTesting regex, trying algorithms, debugging small functionsRuns in a browser sandbox with no filesystem access

Common Style Trade-offs

DimensionOption AWhy AOption BWhy B
Indentation2 spacesFront-end default; saves horizontal space when nesting is deep4 spacesPreferred by Python and some back ends; hierarchy is clearer
IndentationSpacesRenders identically in every editorTabWidth is configurable, but mixing it with spaces breaks alignment
QuotesSingle quotesCommon in JS and Python; safer inside HTML attributesDouble quotesRequired by JSON; conventional for JSX attributes
Line EndingsSemicolons onAvoids edge cases in automatic semicolon insertionSemicolons offTerser, but lines starting with ( [ ` need care

Frequently Asked Questions

Does formatting change how code runs?

A proper formatter works purely at the lexical level and never alters syntax, so behaviour is unchanged. Two real risks remain. The first is automatic semicolon insertion: in a semicolon-free JavaScript style, a line beginning with a bracket, square bracket or backtick can be joined onto the previous one, and re-flowing lines can expose this. The second is that minification is the inverse of formatting — it strips whitespace and line breaks, so if the code relies on semicolons they must be complete before minifying. A safe habit is to run tests or a linter after formatting.

Should I choose XML or JSON?

Default to JSON for new work unless you have a concrete reason otherwise. JSON is lighter, has clearer types, interoperates natively with JavaScript and is generally faster to parse. XML still wins where you need schema validation, namespace isolation, mixed content with attributes, or integration with an existing enterprise system — much of finance and government still speaks SOAP or XML. XML also supports comments, which standard JSON does not, and that occasionally matters for human-readable configuration.

Is running JavaScript in a web page safe?

It depends on where the code came from. The browser execution environment is sandboxed: it cannot read or write local files and cannot reach cross-origin resources, so running your own snippets is safe. The risk is pasting code of unknown provenance, which could issue network requests that exfiltrate data or act within the current page context. Run only code you wrote or trust, and never handle secrets or real data in an online runner.

Our team cannot agree on indentation. What should we do?

Do not settle it by discussion — settle it with tooling. Pick a mainstream style (two spaces for front-end work, four for Python is the least friction starting point), encode it in the editor config and the formatter config file, commit that file, and let formatting happen automatically on save. The point is automation rather than consensus: with a committed config, new members never need to know the history of the argument. What remains for human judgement is naming and structure, which no formatter can decide.