--> pinefixer: How to Format Messy Pine Script Code (A Practical Indentation Guide)
blog

How to Format Messy Pine Script Code (A Practical Indentation Guide)

How to format messy Pine Script code

Pine Script uses indentation to define code blocks — similar to Python, and very different from languages like JavaScript or C++ that use curly braces. If you've ever pasted in a script from a forum and watched it explode into a wall of syntax errors, inconsistent indentation is usually the reason. Here's how the system actually works.

The Core Rule: Indentation Defines Structure

A block of code that belongs inside an if, for, while, or a custom function's body must be indented deeper than the line that opened it, and every line within that block must share the same indentation level. There are no braces or explicit block-end markers — the whitespace itself is the syntax.

if close > open
    strategy.entry("Long", strategy.long)
    label.new(bar_index, high, "Bullish")

Both lines under the if are indented by 4 spaces, so both belong to that block. If the second line had only 2 spaces of indentation, or used a tab instead of spaces, Pine's parser can misread where the block actually ends.

Never Mix Tabs and Spaces

This is the single most common cause of formatting-related compile errors. A script that looks perfectly aligned in your editor can still fail to compile if some lines use tabs and others use spaces — most editors render both identically, so the mismatch is invisible until the compiler chokes on it.

Pick a Consistent Indent Width and Stick to It

4 spaces per indent level is the most common convention and generally the easiest to read. Whatever width you pick, every nested level should be a consistent multiple of it — 4, 8, 12, and so on. Inconsistent widths (3 spaces here, 5 there) don't always break compilation, but they make nested logic much harder to follow visually, which is its own source of bugs.

Watch Indentation on Multi-Line Function Calls

When a function call is split across multiple lines — common with request.security() or long table.cell() calls — the continuation lines need enough indentation to signal they're a continuation, not a new block. Under-indenting these is a frequent source of confusing "no viable alternative" errors.

Trailing Whitespace and Blank Lines

Trailing spaces at the end of a line rarely cause compile errors, but they do make diffs and version comparisons noisy if you're tracking changes over time. Excessive blank lines don't break anything either — they're mostly a readability issue, but a script with wildly inconsistent spacing is much harder to debug when something does go wrong.

Skip doing this by hand

The free Pine Script Formatter normalizes indentation, fixes mixed tabs/spaces, and cleans up operator spacing automatically — paste in messy code, get clean code out, entirely in your browser.

Open the Formatter →