How Code Formatters Work – Build Your Own Like Prettier

Curious how Prettier formats code? Learn how code formatters work under the hood using parsers, ASTs, and code printers. Build your own mini code formatter step by step.

Have you ever wondered how tools like Prettier, Black, or gofmt automatically format messy code into something beautifully consistent?

The secret lies in something called an Abstract Syntax Tree (AST). In this blog post, we’ll dive deep into how code formatters work under the hood—and even show you how to build a basic one yourself.

Whether you're a curious developer or want to build your own formatter, this guide will give you everything you need to get started.

How Code Formatters Work – Build Your Own Like Prettier

🧠 What Is a Code Formatter?

A code formatter is a tool that rewrites source code based on specific styling rules—like indentation, line breaks, spacing, and bracket placement—without changing the code’s logic or functionality.

Examples include:

  • Prettier (JavaScript, TypeScript, HTML, etc.)
  • Black (Python)
  • gofmt (Go)

They work in three core steps:

  • Parse the raw code into an AST
  • Transform or analyze the AST
  • Print the formatted code back as a string

🌳 Step 1: Parsing Code into an AST

An Abstract Syntax Tree (AST) is a structured, tree-like representation of your code. It breaks the code into meaningful components like functions, variables, and expressions.

Let’s use a simple JavaScript code snippet:

Program

 └─ VariableDeclaration

     └─ VariableDeclarator

             ├─ Identifier (greet)

             └─ ArrowFunctionExpression

                       ├─ Identifier (name)

                       └─ BlockStatement

                                 └─ ReturnStatement

                                           └─ BinaryExpression ('Hello ' + name)

🔄 Step 2: Transforming / Traversing the AST

Once you have an AST, a formatter can traverse it and apply formatting rules like:

  • Wrapping long lines
  • Adding/removing semicolons
  • Aligning indentation
  • Grouping multi-line expressions

For example:

  • If a function body has only one return statement, print it in one line.
  • If a block exceeds a set line length (e.g., 80 characters), break it into multiple lines.

🖨️ Step 3: Printing the Code

After applying all formatting rules, the formatter prints the final output as a code string.

This is not just JSON.stringify(AST)—you need a custom printer that understands how to convert syntax trees into styled text.

Prettier uses a system called doc printing, where it builds up virtual layout rules before converting them into a string.

🔗 Don’t Want to Build One? Use Ours!

If you just want to format your code instantly—without dealing with ASTs or building tools—use CodeFormatting.com.

  • Supports JavaScript, Python, HTML, SQL, Go, and more
  • No setup, no installs—just paste and format